bash - 将 If 条件写为函数
问题描述
我正在尝试将 If 条件编写为函数,但我不确定这是否可能。
以下案例:
文件 1
if_exit()
{
if $1; then
echo "$2"
exit 1
fi
}
文件2
source File1
SUUSER=$(whoami)
if_exit "[ $SUUSER != 'root' ]" "Please run the script as root"
说明:我想编写一个函数,其中包括 If 条件(此处使用的简短示例)。然后我想用上面代码示例中提到的不同的东西来调用该函数,或者:
if_exit "[ $(lsb_release -is) != 'Debian' ] && [ $(lsb_release -cs) != 'stretch' ]" "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' ]
还要注意我们如何将诊断打印到标准错误,并注意包含导致打印诊断的脚本的名称。
推荐阅读
- javascript - JavaScript 如何结合 getElementsByName 和 getElementsById (选择所有复选框)
- azure - Http Trigger Azure函数随机返回404
- python - 在 LSTM tensorflow2.0 中计算给定时间步的输出相对于输入的导数
- twilio - Twilio +将变量传递给函数
- spring-boot - server-deployment.yml 未从 Spring Cloud Data 流服务器中的 server-config.yml 读取值
- javascript - 自定义 Azure DevOps REST API 调用
- heroku - 如何通过 heroku CLI 访问 Heroku 应用程序控制台
- c# - 在c#中使用动态项反序列化json对象
- azure-ad-b2c - Azure B2C 隐式流:在不使用 iFrame 的情况下获取新的访问令牌
- validation - 如何在 vue/element-ui 中验证间隔值