我试图了解参数扩展在 bash 脚本中的作用。
third_party_bash_script
#!/bin/sh
files="${*:--}"
# For my understanding I tried to print the contents of files
echo $files
pkill bb_stream
if [ "x$VERBOSE" != "" ]; then
ARGS=-v1
fi
while [ 1 ]; do cat $files; done | bb_stream $ARGS
当我运行 ./third_party_bash_script
时,它打印的只是一个连字符 -
而没有别的。由于它对我没有意义,我也尝试在终端中尝试它
$ set one="1" two="2" three="3"
$ files="${*:--}"
$ echo $files
one="1" two="2" three="3"
$ set four="4"
$ files="${*:--}"
four="4"
我似乎无法理解它在做什么。有人可以帮助我解释 sh
对 ${*:--}
的解释吗?
最佳答案
"$@"
是传递给脚本的参数的数组,"$*"
是字符串 所有这些参数之间用空格连接起来。
"${*:--}"
是参数字符串(如果提供了)(:-
),否则为 -
否则意味着“从标准输入获取输入”。
"${@:--}"
是参数数组(如果提供)(:-
),否则为 -
否则意味着“从标准输入获取输入”。
$ cat file
foo
bar
$ cat tst.sh
#!/usr/bin/env bash
awk '{ print FILENAME, $0 }' "${@:--}"
当向脚本提供 arg 时,"$@"
包含 "file"
所以这就是调用 awk 时使用的 arg:
$ ./tst.sh file
file foo
file bar
当脚本没有提供 arg 时,"$@"
为空,因此 awk 使用 -
调用(意思是从标准输入读取),因为它是 arg:
$ cat file | ./tst.sh
- foo
- bar
在这种情况下,您几乎总是希望使用 "${@:--}"
而不是 "${*:--}"
,请参阅 https://unix.stackexchange.com/questions/41571/what-is-the-difference-between-and关于 "$@"
与 "$*"
的更多信息。
关于bash - 问题理解 bash 脚本中的参数扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70467419/