should I avoid bash -c, sh -c, and other shells' equivalents in my shell scripts?

后端 未结 2 1083
余生分开走
余生分开走 2021-01-07 05:11

Consider the following code:

#!/bin/bash -x
VAR=\'1 2 3\'
bash -c \"echo \"\\$$VAR\"\"
eval \"echo \"\\$$VAR\"\"
bash -c \"echo \\\"\\$$VAR\\\"\"
eval \"echo         


        
2条回答
  •  逝去的感伤
    2021-01-07 06:03

    As far as I am aware, there is no reason to use bash -c from a bash shell. Using it will start a new process, which is expensive.

    You can use eval, which doesn't start a new process. If you want a sub-shell (for example, to preserve the environment) you can use parentheses.

    Normally, bash -c (or other shells with -c) is used to execute a command from another non-shell environment (or perhaps a DSL interpreted by a shell) where shell expansion of the arguments is required. In the old days, you might use it with execvp in a C program, for example. These days, there are usually ways of running a command using a shell in most environments.

提交回复
热议问题