[英]Pass arguments from command Line and from function inside shell script
I want know weather it is possible to pass arguments from command line and from the function inside a shell script 我想知道天气有可能从命令行和shell脚本中的函数传递参数
I know its is possible to pass a argument from command line to shell script using 我知道可以使用命令行将参数从命令行传递到shell脚本
$1 $2 ..
But my problem is my shell script needs to accept arguments from the command line as well as the function inside the shell script . 但是我的问题是我的shell脚本需要接受命令行以及shell脚本中的函数的参数。
find my shell script below 在下面找到我的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"
I execute my shell script by passing 我通过传递执行我的shell脚本
sudo sh test.sh firstargument secondargument thirdargument
You can forward the original arguments with: 您可以使用以下命令转发原始参数:
...
coreExtraction () {
extractZipFiles "$@" some/location some/other/location
}
coreExtraction "$@"
...
To access the original script arguments from inside the function, you have to save them before you call the function, for instance, in an array: 要从函数内部访问原始脚本参数,必须在调用函数之前保存它们,例如在数组中:
args=("$@")
some_function some_other_args
Inside some_function
, the script args will be in ${args[0]}
, ${args[1]}
, and so on. 在
some_function
内部,脚本args将位于${args[0]}
, ${args[1]}
等中。 Their number will be ${#a[@]}
. 他们的号码将是
${#a[@]}
。
Just pass the arguments from the command line invocation to the function 只需将参数从命令行调用传递给函数
coreExtraction "$1" "$2" "$3"
# or
coreExtraction "$@"
and add the other arguments to them 并添加其他参数
extractZipFiles "$@" some/location some/other/location
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.