GilmoreGirling
GilmoreGirling

Reputation: 151

Store output of command in variable where the command is already executed/stored in it's own variable - bash script

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.

Upvotes: 0

Views: 1915

Answers (1)

user1934428
user1934428

Reputation: 22225

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[@]}" )

Upvotes: 1

Related Questions