build command by concatenating string in bash

It all depends on when things get evaluated. When you type $cmd, the whole rest of the line is passed as arguments to the first word in $cmd.

walt@spong:~(0)$ a="cat /etc/passwd"
walt@spong:~(0)$ b="| wc -l"
walt@spong:~(0)$ c="$a $b"
walt@spong:~(0)$ echo $c
cat /etc/passwd | wc -l
walt@spong:~(0)$ $c
cat: invalid option -- 'l'
Try 'cat --help' for more information.
walt@spong:~(1)$ eval $c
62
walt@spong:~(0)$ a="echo /etc/passwd"
walt@spong:~(0)$ c="$a $b"
walt@spong:~(0)$ echo $c
echo /etc/passwd | wc -l
walt@spong:~(0)$ $c
/etc/passwd | wc -l
walt@spong:~(0)$ $c |od -bc
0000000 057 145 164 143 057 160 141 163 163 167 144 040 174 040 167 143  
          /   e   t   c   /   p   a   s   s   w   d       |       w   c  
0000020 040 055 154 012  
              -   l  \n  
0000024
walt@spong:~(0)$ eval $c
1  

This shows that the arguments passed to the echo command are: "/etc/passwd", "|" (the vertical bar character), "wc" and "-l".

From man bash:

eval [arg ...]  
    The  args  are read and concatenated together into   
    a single command.  This command is then read and  
    executed by the shell, and its exit status is returned  
    as the value of eval.  If there are no args, or only null  
    arguments, eval returns 0.

One solution to this, for future reference, is to use "eval". This ensures that whatever way the string is interpreted by bash is forgotten and the whole thing is read as if it was typed directly in a shell (which is exactly what we want).

So in the example above, replacing

$cmd

with

eval $cmd

solved it.


@waltinator already explained why this does not work as you expected. Another way around it is to use bash -c to execute your command:

$ comm="cat /etc/passwd"
$ comm+="| wc -l"
$ $comm
cat: invalid option -- 'l'
Try 'cat --help' for more information.
$ bash -c "$comm"
51

Tags:

Bash

Pipe