bashshellvariablessubstitutionquoting

Variable substitution inside if statement


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.


Solution

  • 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
    '