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

后端 未结 2 1750
南笙
南笙 2021-01-17 17:18

I\'m curious why the commmand:

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

Outputs the last ten files in /mydir, but

2条回答
  •  爱一瞬间的悲伤
    2021-01-17 18:04

    You are using double-quotes, so the parent shell is interpolating backticks and variables before passing the argument to /bin/bash.

    Thus, your /bin/bash is receiving 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;'
    

提交回复
热议问题