开发者

How to use OR within (negative) Bash conditions

This section of my script checks whether the distro is either Ubuntu or Arch. The problem is that I cannot figure out what to replace the OR with to make it work. I tried -o and other suggestions from various websites without succes.

if [ ! $(lsb_release -is) == "Ubuntu" O开发者_C百科R "Arch" ]; then
 echo "Neither Ubuntu nor Arch!"
 read -p "Continue anyway(y/N)? "
 sleep 0
 [ "$REPLY" == "y" ] || exit
fi


You can use something like:

rel="$(lsb_release -is)"
if [[ "${rel}" != "Ubuntu" && "${rel}" != "Arch" ]]; then
   # Neither Ubuntu nor Arch
fi


Use a case/esac construct

case $(lsb_release -is) in
  Ubuntu|Arch ) echo "Ubuntu or Arch found";;
  * ) 
 echo "Neither Ubuntu nor Arch!"
 read -p "Continue anyway(y/N)? "
 sleep 0
 [ "$REPLY" == "y" ] || exit
 ;;
esac


Closest to your original code would be:

if [[ ! $(lsb_release -is) =~ Ubuntu|Arch ]]; then 
    echo "Neither Ubuntu nor Arch!"
    read -p "Continue anyway(y/N)? "
    sleep 0
    [ "$REPLY" == "y" ] || exit; 
fi

This uses the match operator introduced in bash 3. Also note that the above is valid in bash 3.2, prior to that you need to use quotes for the pattern.

if you don't have bash 3 you can use grep

if ! lsb_release -is| egrep -q 'Ubuntu|Arch'; then 
    echo "Neither Ubuntu nor Arch!"
    read -p "Continue anyway(y/N)? "
    sleep 0
    [ "$REPLY" == "y" ] || exit; 
fi

Note that -q is a non-standard option of grep


To answer my own question, here is a slightly longer but more flexible way of achieving the same result.

rel="$(lsb_release -is)"
if [[ "${rel}" = "Arch" ]]; then
    echo "It's Arch"
  elif [[ "${rel}" = "Ubuntu" ]]; then
    echo "It's Ubuntu"
  else
    echo "It's Neither"
    read -p "Continue anyway(y/N)? "
    sleep 0
    [ "$REPLY" == "y" ] || exit
fi
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜