我编写了一个bash脚本,该脚本涉及一组参数,并基于那些我们做不同的事情。因此,在这种情况下,我试图说:
./acorn.sh aisiscore install
但这是我的错误消息,指出第一个参数未进行核对,我应该使用AISiscore或Assets。我检查了拼写,我是正确的,我是否没有正确检查参数?
#!/bin/bash
set -e
function checkCoreArgument(){
if [[ $1 == 'aisiscore' ]]
then
checkAisisArguments
elif [[ $1 == 'assets' || $1 == 'asset' ]]
then
checkAssetsArguments
else
echo "$1 is not recognized. Please try aisiscore or assets"
fi
}
function checkAisisArguments(){
if [[ $2 == 'install' ]]
then
installAisisCore
elif [[ $2 == 'update' ]]
then
updateAisisCore
elif [[ $2 == 'components' ]]
then
callCompomnentsCheck
else
echo "$2 is not recognized. Please try install or update."
fi
}
function checkAssetsArguments(){
if [[ $2 == 'install' ]]
then
installAssets
elif [[ $2 == 'update' ]]
then
updateAisisCore
else
echo "$2 is not recognized. Please use install or update."
fi
}
function installAisisCore(){
cd scripts/install/
chmod +x InstallAisisCore.sh
sudo InstallAisisCore.sh
}
function updateAisisCore(){
cd scripts/update/
chmod +x UpdateAisisCore.sh
sudo UpdateAisisCore.sh
}
function installAssets(){
cd scripts/install/
chmod +x InstallAssets.sh
sudo InstallAssets.sh
}
function updateAisisCore(){
cd scripts/update/
chmod +x UpdateAssets.sh
sudo UpdateAssets.sh
}
function callCompomnentsCheck(){
cd scripts/install
chmod +x InstallComponents.sh
sudo ./InstallComponents.sh
}
###### =============================== [ Application run ] =============== ######
checkCoreArgument #run the app!
它是自上而下的,因此更容易阅读。
函数在$1
,$2
等中获得自己的论点。
checkCoreArgument "$@"
互相调用的功能也是如此。这些功能调用需要明确通过参数。
function checkCoreArgument(){
if [[ $1 == 'aisiscore' ]]
then
checkAisisArguments "$@"
elif [[ $1 == 'assets' || $1 == 'asset' ]]
then
checkAssetsArguments "$@"
else
echo "$1 is not recognized. Please try aisiscore or assets"
fi
}
另外,一个小建议:您可以使用case
语句使这些检查更好。
case $1 in
aisiscore) checkAisisArguments "$@";;
asset|assets) checkAssetsArguments "$@";;
*) echo "$1 is not recognized. Please try aisiscore or assets" >&2;;
esac
这只是约翰·库格曼(John Kugelman)答案的扩展
- 您不需要
function
关键字和()
括号 - 可以"参数化" 有很多剪切代码
#!/bin/bash
set -e
function checkArgs {
case $1 in
aisiscore)
case $2 in
install) install "AisisCore" ;;
update) update "AisisCore" ;;
components) install "Components" ;;
*) echo "$2 is not recognized. Please try install or update." ;;
esac
;;
assets | asset)
case $2 in
install) install "Assets" ;;
update) update "Assets" ;;
*) echo "$2 is not recognized. Please use install or update." ;;
esac
;;
*) echo "$1 is not recognized. Please try aisiscore or assets" ;;
esac
}
function install { cd scripts/install/ && callScript "Install${1}.sh"; }
function update { cd scripts/update/ && callScript "Update${1}.sh"; }
function callScript { chmod +x "$1" && sudo "$1"; }
###### =============================== [ Application run ] =============== ######
checkArgs "$@" #run the app!