嗨,我有一个要求。
我应该运行一个脚本,其中指定的参数数量如下所示。例如./build.sh ab checkout c build de deploy
a,b,c,d,e,f是实例的名称,而checkout,build,deploy是进程的名称。
因此,我可以使用任何进程来运行任何实例。
现在告诉我如何将这些参数分开并在shell脚本中使用它们。
如果参数的类型相似,我可以在数组中使用它们,并使用for循环和switch大小写检查每个参数。
在我的情况下,我必须将参数分开并使其像
需要形成一些动态数组和类似的操作
如果有其他实现方法,请建议我,并向我提供解决方案。
老派的POSIX外壳:
#!/bin/sh
# Note: Inside the functions, $@, $1 etc. refer to the arguments to the function,
# whereas outside they refer to the arguments to the whole script.
foo() {
echo foo $@
}
bar() {
echo bar $3 $2 $1
}
PARAMS=
while [ $# -gt 0 ]; do # while there are arguments
case "$1" in # check if the front argument is a command
foo) # if so, run it with the previously cached parameters
foo $PARAMS # (see below)
PARAMS=
;;
bar)
bar $PARAMS
PARAMS=
;;
*) # if it is not a command, cache the parameter in the
PARAMS+=" $1" # $PARAMS variable
;;
esac
shift # shift the arguments back; what was $2 is now $1
done
称为./foo.sh 1 2 foo 3 4 5 bar
,这给出了
foo 1 2
bar 5 4 3
如果您需要使用bash数组,则其语法为
PARAMS=() # instead of PARAMS=
PARAMS+=("$1") # instead of PARAMS+=" $1"
${PARAMS[0]} # instead of $1, analogous for $2, $3 etc.
其余部分保持不变,当然,您可以使用参数数组调用函数以外的其他事情。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句