[英]Pass arguments from command Line and from function inside shell script
我想知道天气有可能从命令行和shell脚本中的函数传递参数
我知道可以使用命令行将参数从命令行传递到shell脚本
$1 $2 ..
但是我的问题是我的shell脚本需要接受命令行以及shell脚本中的函数的参数。
在下面找到我的shell脚本
#!/bin/bash
extractZipFiles(){
sudo unzip "$4" -d "$5"
if [ "$?" -eq 0 ]
then
echo "==>> Files extracted"
return 0
else
echo "==>> Files extraction failed"
echo "$?"
fi
}
coreExtraction(){
extractZipFiles some/location some/other/location
}
coreExtraction
echo "====> $1"
echo "====> $2"
echo "====> $3"
echo "====> $4"
echo "====> $5"
我通过传递执行我的shell脚本
sudo sh test.sh firstargument secondargument thirdargument
您可以使用以下命令转发原始参数:
...
coreExtraction () {
extractZipFiles "$@" some/location some/other/location
}
coreExtraction "$@"
...
要从函数内部访问原始脚本参数,必须在调用函数之前保存它们,例如在数组中:
args=("$@")
some_function some_other_args
在some_function
内部,脚本args将位于${args[0]}
, ${args[1]}
等中。 他们的号码将是${#a[@]}
。
只需将参数从命令行调用传递给函数
coreExtraction "$1" "$2" "$3"
# or
coreExtraction "$@"
并添加其他参数
extractZipFiles "$@" some/location some/other/location
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.