同步阅读进度,多语言翻译,过滤屏幕蓝光,评论分享,更多完整功能,更好读书体验,试试 阅读 ‧ 电子书库
Quoting with $@ and $*
Now that we have this background, let's take a closer look at "$@" and "$*". These variables are two of the shell's greatest idiosyncracies, so we'll discuss some of the most common sources of confusion.
Why are the elements of "
$*" separated by the first character of
IFS instead of just spaces? To give you output flexibility. As a simple example, let's say you want to print a list of positional parameters separated by commas. This script would do it:
IFS=,
echo "$*"
Changing
IFS in a script is risky, but it's probably OK as long as nothing else in the script depends on it. If this script were called
arglist, then the command
arglist alice dormouse hatter would produce the output
alice,dormouse,hatter. Chapter 5 and Chapter 10 contain other examples of changing
IFS.Why does "
$@" act like N separate double-quoted strings? To allow you to use them again as separate values. For example, say you want to call a function within your script with the same list of positional parameters, like this:
function countargs
{
echo "$# args."
}
Assume your script is called with the same arguments as
arglist above. Then if it contains the command
countargs "
$*", the function will print
1 args. But if the command is
countargs "
$@", the function will print
3 args.