19

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

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

表示 4 不是命令。

4

3 回答 3

35

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.

于 2012-12-07T11:56:17.250 回答
3

您可以通过使用第四个参数再次调用脚本来做您想做的事情:

if [ -z "$4" ]; then
   $0 "$1" "$2" "$3" "$3"
   exit $?
fi
echo $4

调用上面的脚本./script.sh one two three会输出:

于 2012-12-07T11:58:26.017 回答
1

这可以通过直接分配到具有导出/导入类型机制的辅助数组来完成:

set a b c "d e f" g h    
thisArray=( "$@" )
thisArray[3]=4
set -- "${thisArray[@]}"
echo "$@"

输出'abc 4 g h'

于 2019-02-19T08:03:34.150 回答