理解 bash 脚本中的参数扩展时出现问题

AFP*_*AFP 4 parameters bash shell

我试图了解参数扩展在 bash 脚本中的作用。

第三方bash脚本

#!/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
Run Code Online (Sandbox Code Playgroud)

当我运行时./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"
Run Code Online (Sandbox Code Playgroud)

我似乎无法理解它在做什么。有人可以帮助我解释${*:--}by thesh吗?

Ed *_*ton 7

"$@"是传递给脚本的参数数组"$*",是所有这些参数的字符串,中间用空格连接。

"${*:--}"是参数字符串(如果提供了任何参数:-),否则-表示“从 stdin 获取输入”。

"${@:--}"是参数数组(如果提供了任何参数:-),否则-表示“从 stdin 获取输入”。

$ cat file
foo
bar
Run Code Online (Sandbox Code Playgroud)

$ cat tst.sh
#!/usr/bin/env bash

awk '{ print FILENAME, $0 }' "${@:--}"
Run Code Online (Sandbox Code Playgroud)

当向脚本提供 arg 时,"$@"包含"file"以下内容,这就是调用 awk 时使用的 arg:

$ ./tst.sh file
file foo
file bar
Run Code Online (Sandbox Code Playgroud)

当没有向脚本提供 arg 时,"$@"它是空的,因此 awk 被调用-(意思是从 stdin 读取),因为它是 arg:

$ cat file | ./tst.sh
- foo
- bar
Run Code Online (Sandbox Code Playgroud)

您几乎总是想在这种情况下使用"${@:--}"而不是,请参阅https://unix.stackexchange.com/questions/41571/what-is-the-difference- Between-and 有关vs的更多信息。"${*:--}""$@""$*"