【发布时间】:2012-11-25 14:08:15
【问题描述】:
如何在 Bash 中为位置参数赋值?我想为默认参数赋值:
if [ -z "$4" ]; then
4=$3
fi
表示4不是命令。
【问题讨论】:
如何在 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。
【讨论】:
你可以通过第四个参数再次调用你的脚本来做你想做的事:
if [ -z "$4" ]; then
$0 "$1" "$2" "$3" "$3"
exit $?
fi
echo $4
像./script.sh one two three这样调用上面的脚本会输出:
三个
【讨论】:
./$0 将不起作用,$0 本身应该没问题,这适用于 ./script 和 /usr/local/bin/script 等。
这可以通过直接分配到具有导出/导入类型机制的辅助数组来完成:
set a b c "d e f" g h
thisArray=( "$@" )
thisArray[3]=4
set -- "${thisArray[@]}"
echo "$@"
输出'a b c 4 g h'
【讨论】: