bash - 分配给位置参数

标签 bash positional-parameter

<分区>

如何在 Bash 中为位置参数赋值?我想为默认参数赋值:

if [ -z "$4" ]; then
   4=$3
fi

表示4不是命令。

最佳答案

内置的set是设置位置参数的唯一方法

$ set -- this is a test
$ echo $1
this
$ echo $4
test

其中 -- 防止看起来像选项的东西(例如 -x)。

在您的情况下,您可能需要:

if [ -z "$4" ]; then
   set -- "$1" "$2" "$3" "$3"
fi

但它可能会更清楚

if [ -z "$4" ]; then
   # default the fourth option if it is null
   fourth="$3"
   set -- "$1" "$2" "$3" "$fourth"
fi

您可能还想查看参数计数 $# 而不是测试 -z

关于bash - 分配给位置参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13762370/

相关文章:

linux - bash - 自动编译的正确方法

linux - 如何计算 Bash 中字符串中的单词数

外部脚本函数上的 bash 命令替换收到不正确的退出状态

bash - 如何禁用 bash 中的特殊字符?

bash - 如何将位置参数传递给交互式 bash session

bash - 在 Bash 中传递 -e 和 -n 作为位置参数

linux - 使用 wget 检查 ftp 上传并在必要时重试

powershell - 函数参数位置突然表现得很奇怪

linux - 在 Linux 中将位置参数从脚本传递到下标的最佳方式

windows - 打开 git bash shell 窗口,执行命令并在 term 信号后保持