Bash Function return values in if ...; then statement

use*_*898 0 bash function conditional-statements

I'm in the process to enable the firewall on a VM. Initially the firewall is in a masked state. I use two functions

function status_firewall() {
  RET_VAL=" "
  STATUS=$(systemctl status firewalld)
  MASKED=$(grep -e "masked" <<< $STATUS)
  M_RET=$?

  DEAD=$(grep -e "dead" <<< $STATUS)
  D_RET=$?
  logging "M_RET and D_RET: $M_RET, $D_RET"
  if [ "${M_RET}" -eq "0" ]; then
    RET_VAL=1
  elif [ "${D_RET}" -eq "0" ]; then
    RET_VAL=2
  else
    RET_VAL=0
  fi
  echo ${RET_VAL}
}
Run Code Online (Sandbox Code Playgroud)

echo statement prints value "1" if firewall is masked

function check_firewall() {
  FIREWALL=$(status_firewall)
  logging "Firewall status in check_firewall: ${FIREWALL}"
  if [ "$(status_firewall)" -eq "0" ]; then
    logging "Firewalld service already running"
    RET_VAL=0
  elif [ "$(status_firewall)" -eq "1" ]; then
     ...
  elif
     ...
  fi
Run Code Online (Sandbox Code Playgroud)

I get the correct MASKED and DEAD status value (0, 0) status_firewall() { ... } However, when checking for the return values in check_firewall() { .. } I get the following integer error: integer expression expected

When checking the return value in: check_firewall() it lists: Firewall status: ? firewalld.service Loaded: masked (/dev/null) Active: inactive (dead)

How come the first function supposedly returns value "1" but in the second function it lists the return value as the output of the command: systemctl status firewalld

che*_*ner 6

首先,status_firewall通过使用返回值而不是写入标准输出进行简化,并在case语句中使用模式匹配而不是调用grep。

status_firewall() {
    status=$(systemctl status firewalld)
    case $status in
        *masked*) rv=1 ;;
        *dead*)   rv=2 ;;
        *) rv=0 ;;
    esac
    return $rv
}
Run Code Online (Sandbox Code Playgroud)

然后 check_firewall,只需检查的退出状态即可status_firewall。

check_firewall() {
  status_firewall
  case $? in
    0) logging "Firewalld service already running" ;;
    1) ... ;;
    2) ... ;;
  esac
}
Run Code Online (Sandbox Code Playgroud)

实际上,您可以status_firewall完全取消:

check_firewall() {
  case $(systemctl status firewalld) in
    *masked*) ... ;;
    *dead*) ... ;;
    *) logging "Firewalld service already running" ;;
  esac
}
Run Code Online (Sandbox Code Playgroud)