Code example below shows the problem:
bash -c "$(echo 'ls | wc -l')" # Working "$(echo 'ls | wc -l')" # Not working $(echo 'ls | wc -l') # Not working 'ls | wc -l' # Not working 'ls' # Working ls | wc -l # Obviously working
What am I missing here?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
If you give the shell a text string to execute, it will be able to do so if it happens to correspond to a command, like
"ls -l" is not the name of a command).
Your first example works because the
echo in the command execution is executed by the invoking shell, generating
bash -c "ls | wc -l". The pipeline is then executed by
bash -c, which is fine.
The second, third and fourth example doesn't work since an extra step of evaluation needs to happen on the generated text string
ls | wc -l.
eval would do this for you.
"ls -l" or
"ls | wc -l" does not work is that quote removal happens after word splitting in the evaluation of the command line.
$(echo 'ls | wc -l') doesn't work is that command substitution also happens after word splitting.