有没有一种方法可以在Bash脚本中更改命令行参数?例如,一个Bash脚本被调用如下:
./foo arg1 arg2
有没有一种方法可以在脚本内改变arg1的值?类似于:
$1="chintz"
有没有一种方法可以在Bash脚本中更改命令行参数?例如,一个Bash脚本被调用如下:
./foo arg1 arg2
有没有一种方法可以在脚本内改变arg1的值?类似于:
$1="chintz"
您需要重置所有的参数。例如修改参数$3
:
$ set -- "${@:1:2}" "new_arg3" "${@:4}"
基本上,您可以将set 所有 参数设置为它们当前的值,除了您想要更改的参数。 set --
在 POSIX 7 中也被指定。
"${@:1:2}"
表示法 被扩展为从偏移量1
(即$1
)开始的两个位置参数(因此在符号中有2
)。 在这种情况下,它是"$1" "$2"
的简写,但是当您想替换例如"${17}"
时,它会更加有用。
为了提高可读性和可维护性,您最好将$1
和$2
分配给更有意义的变量(比如说input_filename = $1
和output_filename = $2
之类的),然后重写其中一个变量(input_filename = 'chintz'
),以保留脚本中的输入不变,以防在其他地方需要使用。
我知道这是一篇老的文章,但我发现thkala的答案非常有用,因此我借鉴了这个想法并稍微扩展了一下,使我能够为任何未定义的参数添加默认值-例如:
# set defaults for the passed arguments (if any) if not defined.
#
arg1=${1:-"default-for-arg-1"}
arg2=${2:-"default-for-arg-2"}
set -- "${arg1}" "${arg2}"
unset arg1 arg2
我希望这对其他人有用。
set --
在bash中更改命令行参数$1
,$2
等作为对Ask Ubuntu上@Radu Rădeanu的主要答案和Stack Overflow上@thkala的主要答案的补充,我想添加一个非常简单的示例,以一次设置多个参数,如下所示:
# set arguments `$1`, `$2`, and `$3` to these respective values
set -- "one" "two" "three"
echo "$1 $2 $3"
输出:
one two three
set -- "one" "two" "three" "${@:4}"
"${@:4}"
切片语法:Unix & Linux: Bash: slice of positional parameters。请参阅该答案以获取有关bash数组切片的更多详细信息。以下是其中的一小段代码:
# array slicing basic format 1: grab a certain length starting at a certain
# index
echo "${@:2:5}"
# │ │
# │ └────> slice length
# └──────> slice starting index
# array slicing basic format 2: grab all remaining array elements starting at a
# certain index through to the end
echo "${@:2}"
# │
# │
# └──────> slice starting index
所以,在@thkala的主要答案中,包括了这个内容:set -- "${@:1:2}" "new_arg3" "${@:4}"
...解释是"${@:1:2}"
获取前两个参数,"new_arg3"
将其作为新的第三个参数插入,而"${@:4}"
从第4个参数到最后一个参数获取所有参数,从而仅更改参数3并保持所有其他参数不变。
要获取有关内置bash命令set
的帮助,请参阅help set
或在此处在线查看:https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#The-Set-Builtin
help set
显示--
参数的以下内容:
-- Assign any remaining arguments to the positional parameters.
If there are no remaining arguments, the positional parameters
are unset.
eval
。 - cxw