fed*_*qui 10
是!
$ cat a.sh
echo "$@"
echo $@
Run Code Online (Sandbox Code Playgroud)
我们来吧:
$ ./a.sh 2 "3 4" 5
2 3 4 5 # output for "$@"
2 3 4 5 # output for $@ -> spaces are lost!
Run Code Online (Sandbox Code Playgroud)
如您所见,使用时$@,参数会在用作参数时"丢失"某些内容.请参阅 - 例如 - 我刚刚分配了一个变量,但echo $ variable显示了其他内容,以便对此进行详细说明.
@
($ @)从一个开始扩展到位置参数.当扩展发生在双引号内时,每个参数都会扩展为单独的单词.也就是说,"$ @"相当于"$ 1""$ 2".... 如果双引号扩展发生在一个单词中,则第一个参数的扩展与原始单词的开头部分连接,最后一个参数的扩展与原始单词的最后一部分连接.当没有位置参数时,"$ @"和$ @扩展为空(即,它们被删除).
将$ @传递给命令会将所有参数传递给命令.如果参数包含空格,则命令会将该参数视为两个独立的参数.
将"$ @"传递给命令会将所有参数作为引用字符串传递给命令.该命令将看到一个包含空格的参数作为包含空格的单个参数.
为了轻松可视化差异,编写一个函数,在循环中打印所有参数,一次一个:
#!/bin/bash
loop_print() {
while [[ $# -gt 0 ]]; do
echo "argument: '$1'"
shift
done
}
echo "#### testing with \$@ ####"
loop_print $@
echo "#### testing with \"\$@\" ####"
loop_print "$@"
Run Code Online (Sandbox Code Playgroud)
用这个脚本调用
<script> "foo bar"
Run Code Online (Sandbox Code Playgroud)
将产生输出
#### testing with $@ ####
argument: 'foo'
argument: 'bar'
#### testing with "$@" ####
argument: 'foo bar'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6282 次 |
| 最近记录: |