Normally when a parameter is passed to a shell script, the value goes into
Normally when a parameter is passed to a shell script, the value goes into ${1} for the first paramater, ${2} for the second, etc.
通常,当参数传递给shell脚本时,第一个参数的值为${1},第二个参数为${2},等等。
How can I set the default values for these parameters, so if no parameter is passed to the script, we can use a default value for ${1}?
如何为这些参数设置默认值,以便如果没有将参数传递给脚本,我们可以为${1}使用默认值?
4 个解决方案
#1
12
You can't, but you can assign to a local variable like this: ${parameter:-word} or use the same construct in the place you need $1. this menas use word if _paramater is null or unset
你不能,但是你可以像这样分配一个局部变量:${参数:-word}或者在你需要$1的地方使用相同的结构。如果_paramater为null或未设置,这个menas会使用word
Note, this works in bash, check your shell for the syntax of default values
注意,这在bash中工作,检查shell的默认值语法。
#2
9
You could consider:
你可以考虑:
set -- "${1:-'default for 1'}" "${2:-'default 2'}" "${3:-'default 3'}"
The rest of the script can use $1, $2, $3 without further checking.
脚本的其余部分可以使用$1、$2、$3,无需进一步检查。
Note: this does not work well if you can have an indeterminate list of files at the end of your arguments; it works well when you can have only zero to three arguments.
注意:如果在您的参数末尾有一个不确定的文件列表,那么这个方法就不适用了;当你只有0到3个参数时,它就能很好地工作。
#3
4
#!/bin/sh
MY_PARAM=${1:-default}
echo $MY_PARAM
#4
0
Perhaps I don't understand your question well, yet I would feel inclined to solve the problem in a less sophisticated manner:
也许我不太理解你的问题,但我想用一种不那么复杂的方式来解决这个问题:
! [[ ${1} ]] && declare $1="DEFAULT"
Hope that helps.
希望有帮助。
for the first paramater, for the second, etc. Normally when a parameter is passed to a shell