1

I pass a list of commands to a bash script through an environment variable as shown in the example below:

CMDS=' date > date.txt cat date.txt date | rev ' script 

What is the correct way to execute these commands in the bash script ?

I did the following and it seams to work. Is it correct ?

#! /bin/bash bash -c "$CMDS" 
3
  • As long as the string CMDS is not using another ' it should be correct. Example for a problematic CMDS string would be: CMDS='echo "hello world"; echo ';echo $0'; echo "good bye"'. Commented Jan 18, 2024 at 11:23
  • @paladin thank you very much. Is there a way to avoid this limitation ? I use this to filter forced commands in ssh authorized_keys file. I use a script that only accepts to execute commands listed in a file in the remote host. Commented Jan 19, 2024 at 12:26
  • Use " instead of ' and escape everything which is problematic, like so: CMDS="echo \"hello world\"; echo ';echo \$0'; echo \"good bye\"". Commented Jan 19, 2024 at 12:41

1 Answer 1

0

While it is correct, as long as you escape any single quotes in the CMDS with a single backslash, why not put the commands in a function instead?

function bob() { command1 command2 command3 } bob 

You can even pass arguments and read return codes.

function bob() { echo $1 echo $2 return 5 } bob param1 param2 echo $? 

Using functions avoids calling a new instance of bash shell to run the commands.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.