从命令行和shell脚本内的函数传递参数 [英] Pass arguments from command Line and from function inside shell script
本文介绍了从命令行和shell脚本内的函数传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否可以从命令行和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[0]}
、${args[1]}
中,依此类推。它们的编号将是${#a[@]}
。
这篇关于从命令行和shell脚本内的函数传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文