Variable substitution inside if statement

92 views Asked by At

I have the following bash script that I do not have control over:

set -x
echo "$CMD"
if ${CMD}; then
  echo "Success"
fi

I'm trying to run the following command: bash -c "echo first && true". How do I pass it in for CMD, any ideas? Note here both echo and true are replacements for my actual more complex commands, here I replaced with these two trivial ones to highlight the issue in a simpler way.

I'd expect it to work with just:

❯ env CMD='bash -c "echo first && true"' bash magic.sh
+ echo 'bash -c "echo first && true"'
bash -c "echo first && true"
+ bash -c '"echo' first '&&' 'true"'
first: -c: line 1: unexpected EOF while looking for matching `"'

But it seems the variable substitution doesn't allow this, as the arguments get quoted.

2

There are 2 answers

1
jhnc On BEST ANSWER

You can store all the commands in a shell script that exits with the appropriate code:

$ printf '#!/bin/bash\necho first && true\n' > /path/to/myscript
$ chmod +x /path/to/myscript
$ CMD=/path/to/myscript bash magic.sh

You can also declare a shell function:

bash -c '
    myscript(){
        echo first && true
    }
    CMD=myscript
    . magic.sh
'
2
Joseph Martin On
# Revised using eval and second env-var
# Can another env-var be set as well?
Bash/001> cat test01.sh 
set -x
echo "$CMD"
if ${CMD}; then
  echo "Success"
fi
Bash/001> export BCMD='eval echo first && echo second && echo third && ls -l && true'
Bash/001> export CMD='bash -c $BCMD'
Bash/001> bash test01.sh 
+ echo 'bash -c $BCMD'
bash -c $BCMD
+ bash -c '$BCMD'
first
second
third
total 4
-rwxr-xr-x 1 josep users 55 Dec 27 20:45 test01.sh
+ echo Success
Success