bash 中的“$*”有哪些用例?
What are some use cases of "$*" in bash?
来自 bash 手册页:
"$*"
is equivalent to "cc..."
, where c
is the first character of the value of the IFS
variable.
"$@"
is equivalent to "" ""
...
任何 "$@"
不能代替 "$*"
的例子?
我最喜欢的用途是替换字段分隔符。
$ set -- 'My word' but this is a bad 'example!'
$ IFS=,
$ echo "$*"
My word,but,this,is,a,bad,example!
还有其他替换定界符的方法,但 IFS 和 "$*"
通常是最简单的方法之一。
这些是完全不同的工具,应该在完全不同的情况下使用。一个替代另一个没有合理的问题,因为在任何给定情况下,只有一个或另一个是正确的。
"$*"
当您尝试从参数列表中形成单个字符串参数时最适用——主要用于日志记录(但不是参数之间的划分很重要的情况;然后,"$@"
适用于 print '%q '
之类的东西)。 "$@"
在……好吧,任何其他情况下都很有用。
示例:
die() {
local stat=; shift
log "ERROR: $*"
exit $stat
}
在格式化要传递给 log
的字符串时使用 "$*"
仅使用单个 argv 条目,允许将其他可选的位置参数添加到 log
在未来。
$* 将所有参数扩展为一个单词,参数之间带有 IFS。
$@ 将所有参数扩展为列表。
在名为 list.sh:
的文件中尝试下一个代码
#!/bin/bash
echo "using '$*'"
for i in "$*"
do
echo $i
done
echo "using '$@'"
for i in "$@"
do
echo $i
done
使用它:
./list.sh apple pear kiwi
来自 bash 手册页:
"$*"
is equivalent to"cc..."
, wherec
is the first character of the value of theIFS
variable.
"$@"
is equivalent to"" ""
...
任何 "$@"
不能代替 "$*"
的例子?
我最喜欢的用途是替换字段分隔符。
$ set -- 'My word' but this is a bad 'example!'
$ IFS=,
$ echo "$*"
My word,but,this,is,a,bad,example!
还有其他替换定界符的方法,但 IFS 和 "$*"
通常是最简单的方法之一。
这些是完全不同的工具,应该在完全不同的情况下使用。一个替代另一个没有合理的问题,因为在任何给定情况下,只有一个或另一个是正确的。
"$*"
当您尝试从参数列表中形成单个字符串参数时最适用——主要用于日志记录(但不是参数之间的划分很重要的情况;然后,"$@"
适用于 print '%q '
之类的东西)。 "$@"
在……好吧,任何其他情况下都很有用。
示例:
die() {
local stat=; shift
log "ERROR: $*"
exit $stat
}
在格式化要传递给 log
的字符串时使用 "$*"
仅使用单个 argv 条目,允许将其他可选的位置参数添加到 log
在未来。
$* 将所有参数扩展为一个单词,参数之间带有 IFS。
$@ 将所有参数扩展为列表。
在名为 list.sh:
的文件中尝试下一个代码#!/bin/bash
echo "using '$*'"
for i in "$*"
do
echo $i
done
echo "using '$@'"
for i in "$@"
do
echo $i
done
使用它:
./list.sh apple pear kiwi