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
2 个解决方案
#1
2
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. Their number will be ${#a[@]}
.
在some_function中,脚本args将使用${args[0]}、${args[1]}等等。他们的号码是${#a[@]}。
#2
1
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
#1
2
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. Their number will be ${#a[@]}
.
在some_function中,脚本args将使用${args[0]}、${args[1]}等等。他们的号码是${#a[@]}。
#2
1
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