bash 分配给位置参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13762370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:57:36  来源:igfitidea点击:

Assigning to a positional parameter

bash

提问by Freeman

How can I assign a value to a positional parameter in Bash? I want to assign a value to a default parameter:

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

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

Indicating that 4 is not a command.

表示 4 不是命令。

回答by msw

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

set内置的设置位置参数的唯一途径

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

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

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

In your case you might want:

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

if [ -z "" ]; then
   set -- "" "" "" ""
fi

but it would probably be more clear as

但它可能会更清楚

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

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

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

回答by Nelson

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

您可以通过使用第四个参数再次调用脚本来执行您想要的操作:

if [ -z "" ]; then
   
set a b c "d e f" g h    
thisArray=( "$@" )
thisArray[3]=4
set -- "${thisArray[@]}"
echo "$@"
"" "" "" "" exit $? fi echo

Calling above script like ./script.sh one two threewill output:

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

three

回答by Brian Chrisman

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

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

##代码##

outputs 'a b c 4 g h'

输出“abc 4 gh”