Cannot execute an AWS IOT command formed from a bash script

Viewed 48

I wrote the following bash script to send a command to my IOT device:

#!/bin/bash
# target aws command
# aws iot-data publish --topic 12345678_toDevice --qos 1 --payload ``echo '{"command": "do soemthing 90"}' | base64`` --region us-west-2
mac=$(cat mac.txt)
#echo $mac 
cmd1="aws iot-data publish --topic "
cmd2="_toDevice --qos 1 --payload \`echo '{\"command\": \"dosomething "
cmd3="\"}' | base64\` --region us-west-2"
echo $cmd1$mac$cmd2$1$cmd3
command=$($cmd1$mac$cmd2$1$cmd3)

Basically, the command gets the mac address of the device im trying to communicate with, and forms am aws command string, then executes it.

When I run my script, I get this:

>./setpos.sh 45

usage: aws [options] <command> <subcommand> [<subcommand> ...] [parameters]
To see help text, you can run:

  aws help
  aws <command> help
  aws <command> <subcommand> help

Unknown options: "dosoemthing, 45"}', |, base64`, '{"command":

aws iot-data publish --topic 588E815CA84C_toDevice --qos 1 --payload `echo '{"command": "setDesiredPosition 45"}' | base64` --region us-east-2

If I copy and paste the echo'ed command (last line) into bash, command works???? How do I get bash to format the command correctly so it can execute it from the script???

1 Answers

It looks like you are trying to programmatically generate a command. You can correctly run the command like this:

payload="$(echo "{\"command\": \"dosomething $1\"}" | base64)"
aws iot-data publish --topic "${mac}_toDevice" --qos 1 --payload "$payload" --region us-west-2

If you want to capture the output of running the aws command in a variable, you can do so like this:

payload="$(echo "{\"command\": \"dosomething $1\"}" | base64)"
command="$(aws iot-data publish --topic "${mac}_toDevice" --qos 1 --payload "$payload" --region us-west-2)"
Related