Assigning to a positional parameter

大城市里の小女人 提交于 2019-11-27 22:48:05

The set built-in is the only way to set positional parameters

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

where the -- protects against things that look like options (e.g. -x).

In your case you might want:

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

but it would probably be more clear as

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

you might also want to look at the parameter count $# instead of testing for -z.

Nelson

You can do what you want by calling your script again with a fourth parameter:

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

Calling above script like ./script.sh one two three will output:

three

This can be done with an assignment directly into an auxiliary array with an export/import type mechanism:

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

outputs 'a b c 4 g h'

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!