bash - 问题理解 bash 脚本中的参数扩展

标签 bash shell parameters

我试图了解参数扩展在 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/

相关文章:

python - 计算文本文件中的不同单词 : different results in Shell and Python

php - 期望参数 1 是 mysqli_result,给定的 boolean 值

c++ - boost::stacktrace 打印地址

string - 如何将所有从 'foobar' 开始的行移动到文件末尾?

linux - 表达式为字符串(shell 脚本)

bash - 命令返回数据到变量的返回状态

c++ - 合并功能以获得更清晰的代码?

javascript - 使用NodeJS,head中的javascript无法使用来自服务器的参数

只有在成功 stash 之前,Git才会藏起来

bash - 查找 ffmpeg 安装版本