0

I have a command that is stored in a variable. I would like to execute that command and then store the response of that command in a variable. I'm having an issue with syntax errors for the responseVar=$("{commandVar}") line as it seems to trigger a "no such file or directory" error instead of actually running the command/storing the output in the response variable.

commandVar="curl --location -g --request POST 'https://172.217.25.35/rest-gateway/rest/api/v1/auth/token' --header 'Content-Type: application/json' --header 'Authorization: Basic U0FNcWE6NTYyMFNhbSE=' --data-raw '{"grant_type": "client_credentials"}'"

responseVar=$("{commandVar}")

echo "Response of command: ${responseVar}"

Does anyone know the correct syntax on how I would do this? I need to eventually parse the output of the command which is why I need to store the response in it's own variable.

Rubén
  • 34,714
  • 9
  • 70
  • 166
GilmoreGirling
  • 151
  • 1
  • 2
  • 7
  • 1
    Don't store commands in variables; variables are for data, not executable code. If you really need to store a command, use a function or possibly an array. See [BashFAQ #50: "I'm trying to put a command in a variable, but the complex cases always fail!"](http://mywiki.wooledge.org/BashFAQ/050) and ]"Why does shell ignore quoting characters in arguments passed to it through variables?"](https://stackoverflow.com/questions/12136948/why-does-shell-ignore-quoting-characters-in-arguments-passed-to-it-through-varia) (but ignore all suggestions involving `eval` -- it is a massive bug magnet). – Gordon Davisson Jun 27 '22 at 08:16
  • 1
    Um, why you need this intermediate var? Why not just `responseVar=$( curl ... )` – Ivan Jun 27 '22 at 14:28

1 Answers1

1

You are trying to execute a program named {commandVar}, and this program does not exist in your PATH.

To start with, you better use an array to store your command, each array element holding one command argument:

commandVar=(curl --location -g --request POST 'https://172.217.25.35/rest-gateway/rest/api/v1/auth/token' --header 'Content-Type: application/json' --header 'Authorization: Basic U0FNcWE6NTYyMFNhbSE=' --data-raw '{"grant_type": "client_credentials"}')

With this, you can execute it by

"${commandVar[@]}"

respectively store its standardoutput into a variable like this:

responseVar=$( "${commandVar[@]}" )
user1934428
  • 19,864
  • 7
  • 42
  • 87