首页 > 解决方案 > 将 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"

提前致谢!

标签: bashfunctionif-statementconditional-statements

解决方案


我会重构,这样您就不必在参数周围使用引号。

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' ]

还要注意我们如何将诊断打印到标准错误,并注意包含导致打印诊断的脚本的名称。


推荐阅读