Search code examples
bashshellubuntu-12.04backticks

Valid commands to be used in backticks in bash?


Consider the two commands,

command1="mysql -umyuser -pmypassword -e \"show databases;\";"
command2="cat stackoverflow.txt"

The strings are formed as follows,

echo ${command1} -> mysql -umyuser -pmypassword -e "show databases;";
echo ${command2} -> cat stackoverflow.txt

My aim is to run the command from a variable and store it's result in another.

So what I do is,

result1=`${command1}`
ERROR 1049 (42000): Unknown database 'databases;";'

BUT,

result2=`${command2}` 

works perfectly fine.

When using $() instead of backticks the commands behave the same.

Both, of these commands work perfectly fine when run directly in backquotes instead of a variable.

Why this different behaviour?


Solution

  • The following:

    command1="mysql -umyuser -pmypassword -e \"show databases;\";"
    

    fails because of word splitting. When you say $command1, the shell would interpret it as:

    mysql -umuuser -pmypassword -e '"show' 'databases;";'
    

    So the parameter passed to -e option is "show and not what you thought.

    Make use of functions instead:

    mycommand() {
      mysql -umyuser -pmypassword -e "show databases;"
    }
    

    In the second case, the shell is simply reading the contents of the file and executing it. As such, it works.

    You may also want to refer to Word Splitting in the manual. Also see: I'm trying to put a command in a variable, but the complex cases always fail!.