更新时间:2023-09-27 15:04:04
bash -c 'printf "%s %s %s\n" $0 $1 $2' param1 param2 param3
以上方法有效,但许多人会认为这是一个坏习惯.如果要将代码从-c
字符串复制到脚本,它将失败.同样,如果要将代码从脚本复制到-c
字符串,则会失败.
The above works but many would consider it a bad habit to get into. If you were to copy code from the -c
string to a script, it would fail. Similarly, if you were to copy code from a script to a -c
string, it would fail.
相比之下,$1
具有以下形式,它在-c
字符串中的含义与在脚本或shell函数中的含义相同:
By contrast, with the following form, $1
means the same thing in the -c
string that it would mean in a script or shell function:
bash -c 'printf "%s %s %s\n" $1 $2 $3' _ param1 param2 param3
编程风格的一致性减少了错误.
Consistency of programming style reduces bugs.
通常使用$@
或$*
引用脚本的所有参数.请注意,这些变量不包括$0
:
One customarily refers to all of a script's arguments with $@
or $*
. Note that these variables do not include $0
:
$ bash -c 'echo "$*"' param1 param2 param3
param2 param3
$ bash -c 'echo "$@"' param1 param2 param3
param2 param3
$0
是程序名称在常规脚本中,$0
是脚本的名称.因此,在使用bash -c
时,某些人喜欢为$0
参数使用一些有意义的名称,例如:
$0
is the program nameIn regular scripts, $0
is the name of the script. Consequently, when using bash -c
, some people prefer to use some meaningful name for the $0
parameter, such as:
bash -c 'printf "%s %s %s\n" $1 $2 $3' bash param1 param2 param3
或者:
bash -c 'printf "%s %s %s\n" $1 $2 $3' printer param1 param2 param3
如果-c
字符串生成错误,则此方法具有明显的优势.例如,考虑以下脚本:
This approach has a clear advantage if the -c
string generates an error. For example, consider this script:
$ cat script.sh
#!/bin/bash
bash -c 'grepp misspelling "$1"' BadPgm file.txt
如果运行脚本,将产生以下输出:
If we run the script, the following output is produced:
$ ./script.sh
BadPgm: grepp: command not found
这将错误源标识为bash -c
字符串中的命令.
This identifies the source of the error as the command in the bash -c
string.