How do / bin / bash -c differ from executing a command directly?

I am curious why commmand:

for f in `/bin/ls /mydir | sort | tail -n 10`; do echo $f; done;

List the last ten files in / mydir, but

/bin/bash -c "for f in `/bin/ls /mydir | sort | tail -n 10`; do echo $f; done;"

Output "syntax error near unexpected token" [file in / mydir] '"

+4
source share
2 answers

You use double quotes, so the parent shell interpolates backticks and variables before passing the argument /bin/bash.

This way your /bin/bashgets the following arguments:

-c "for f in x
y
z
...
; do echo ; done;"

which is a syntax error.

To avoid this, use single quotes to pass your argument:

/bin/bash -c 'for f in `/bin/ls /mydir | sort | tail -n 10`; do echo $f; done;'
+5
source

. , , /bin, :

rmdir
sh
sleep
stty
sync
tcsh
test
unlink
wait4path
zsh

:

/bin/bash: -c: line 1: syntax error near unexpected token `sh'
/bin/bash: -c: line 1: `sh'

, ( ), - "". echo, bash -c :

$ echo "for f in `/bin/ls /bin | sort | tail -n 10`; do echo \$f; done"
for f in rmdir
sh
sleep
stty
sync
tcsh
test
unlink
wait4path
zsh; do echo $f; done

, bash -c - sh do!

, , :

$ /bin/bash -c 'for f in `/bin/ls /bin | sort | tail -n 10`; do echo $f; done'
rmdir
sh
sleep
stty
sync
tcsh
test
unlink
wait4path
zsh

, :

$ /bin/bash -c "for f in `/bin/ls /bin | sort | tail -n 10 | tr '\n' ' '`; do echo \$f; done"
rmdir
sh
sleep
stty
sync
tcsh
test
unlink
wait4path
zsh
+2
source

All Articles