Bash 将If条件写为函数
我试图写一个If条件作为函数,我不确定这是否可能 以下情况: 文件1 文件2 说明: 我想写一个函数,其中包括If条件(这里使用的简短示例)。 然后我想用不同的东西调用该函数,如代码示例中所述,或者:Bash 将If条件写为函数,bash,function,if-statement,conditional-statements,Bash,Function,If Statement,Conditional Statements,我试图写一个If条件作为函数,我不确定这是否可能 以下情况: 文件1 文件2 说明: 我想写一个函数,其中包括If条件(这里使用的简短示例)。 然后我想用不同的东西调用该函数,如代码示例中所述,或者: if_exit "[ $(lsb_release -is) != 'Debian' ] && [ $(lsb_release -cs) != 'stretch' ]" "The script only works with Stretch" 提前谢谢 您可能需要使用eval来实现
if_exit "[ $(lsb_release -is) != 'Debian' ] && [ $(lsb_release -cs) != 'stretch' ]" "The script only works with Stretch"
提前谢谢 您可能需要使用
eval
来实现这一点,这通常是您希望不惜一切代价避免的。对于您的用例,我建议:
function die() {
echo "$1"
exit 1
}
[ "$SUUSER" != 'root' ] && die "Please run the script as root"
[ "$(lsb_release -is)" != 'Debian' && "$(lsb_release -cs)" != 'stretch' ] && die "The script only works with Stretch"
我会重构,这样你就不必对参数引用
if_exit()
{
local message=$1
shift
if "$@"; then
echo "$0: $message" >&2
exit 1
fi
}
# Tangentially, don't use upper case for private variables
Suuser=$(whoami)
if_exit "Please run the script as root" [ "$Suuser" != 'root' ]
还要注意我们如何将诊断打印为标准错误,并注意包括导致打印诊断的脚本的名称。当您只有少量检查时,可以使用 [[$SUUSER!='root']&&{echo“请以root身份运行脚本”;echo exit 1;} 当你有很多检查时,我会使用一个
die()
函数,就像@erik_dannenberg写的那样
离题:您应该用小写字母编写自己的shell变量,比如${su_user}
建议使用此函数的一个原因是可能会显示哪个测试失败(将“${su_user}”
与root
进行比较)。当你想要这个的时候,做一个函数,比如
checkroot()
。当您想要支持所有普通特殊字符时,您将承担很多责任。我尝试了一些支持
[…]
语法的东西。你知道这个“解决方案”有什么问题吗
if_exit(){#函数不正确
#先跳过'['
转移
#[左右拆分行]
IFS=“]”read-r testparams errormessage我个人认为这会降低代码的可读性。我不会这样做,因为函数会接收设置并将其存储到消息中。之后,您可以使用shift将另一个返回值切换到“left”?但我如何使用您的解决方案进行这样的比较?如果退出“请使用Buster运行”[$(lsb_release-is)!=“Debian”]&[$(lsb_release-cs)!=“stretch”]对于变量名来说,这是一个很好的提醒:P PS:使用这样的构造来缩短程序代码是不是很糟糕?提前谢谢,您回答了我的初学者问题操作:P!使用此解决方案,参数只能是一个简单的命令。对于复杂的命令,我会选择[$(lsb_release-Is)!='Debian'&&[$(lsb_release-cs)!='stretch']| | die“请与Buster一起运行”
有关die
的更多变体,请参见为什么不在die()
函数中使用echo“$@”
?Ik将帮助那些懒惰的人。
function die() {
echo "$1"
exit 1
}
[ "$SUUSER" != 'root' ] && die "Please run the script as root"
[ "$(lsb_release -is)" != 'Debian' && "$(lsb_release -cs)" != 'stretch' ] && die "The script only works with Stretch"
if_exit()
{
local message=$1
shift
if "$@"; then
echo "$0: $message" >&2
exit 1
fi
}
# Tangentially, don't use upper case for private variables
Suuser=$(whoami)
if_exit "Please run the script as root" [ "$Suuser" != 'root' ]
if_exit() { # incorrect function
# skip first '['
shift
# split line around ]
IFS="]" read -r testparams errormessage <<< "${@}"
if [ ${testparams} ] ; then
echo "Test [ ${testparams% } ] failed: ${errormessage# }"
# exit 1
fi
}
if_exit [ -f non_existing_file ] "file not existing"
su_user="root"
if_exit [ "${su_user}" \!= root ] "Please run the script as root"
echo "Another test with wrong user"
su_user="aeris"
if_exit [ "${su_user}" \!= root ] "Please run the script as root"