分配给位置参数 [英] Assigning to a positional parameter

查看:86
本文介绍了分配给位置参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Bash中为位置参数分配值?我想为默认参数分配一个值:

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

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

指示4不是命令.

推荐答案

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

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

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

其中--可以防止出现类似于选项的内容(例如-x).

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

但可能更清楚

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

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

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

这篇关于分配给位置参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆