我写了一个bash脚本,它接受一组参数,并根据我们做不同的事情.所以在这种情况下我想说:
./acorn.sh aisiscore install
但它转到我的错误消息,指出第一个参数没有重新组合,我应该使用aisiscore或资产.我检查了拼写,我是对的,我没有正确检查参数吗?
#!/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