bash string compare to multiple correct values [duplicate]

会有一股神秘感。 提交于 2019-12-17 15:48:08

问题


i have the following piece of bashscript:

function get_cms {
    echo "input cms name"
    read cms
    cms=${cms,,}
    if [ "$cms" != "wordpress" && "$cms" != "meganto" && "$cms" != "typo3" ]; then
        get_cms
    fi
}

But no matter what i input (correct and incorrect values) it never calls the function again, because I only want to allow 1 of those 3 inputs. I have tried it with || with [ var != value ] or [ var != value1 ] or [ var != value1 ] but nothing works. Can someone point me in the right direction?


回答1:


Instead of saying:

if [ "$cms" != "wordpress" && "$cms" != "meganto" && "$cms" != "typo3" ]; then

say:

if [[ "$cms" != "wordpress" && "$cms" != "meganto" && "$cms" != "typo3" ]]; then

You might also want to refer to Conditional Constructs.




回答2:


If the main intent is to check whether the supplied value is not found in a list, maybe you can use the extended regular expression matching built in BASH via the "equal tilde" operator (see also this answer):

if ! [[ "$cms" =~ ^(wordpress|meganto|typo3)$ ]]; then get_cms ; fi

Have a nice day




回答3:


Maybe you should better use a case for such lists:

case "$cms" in
  wordpress|meganto|typo3)
    do_your_else_case
    ;;
  *)
    do_your_then_case
    ;;
esac

I think for long such lists this is better readable.

If you still prefer the if you can do it with single brackets in two ways:

if [ "$cms" != wordpress -a "$cms" != meganto -a "$cms" != typo3 ]; then

or

if [ "$cms" != wordpress ] && [ "$cms" != meganto ] && [ "$cms" != typo3 ]; then



回答4:


Here's my solution

if [[ "${cms}" != +(wordpress|magento|typo3) ]]; then


来源:https://stackoverflow.com/questions/21157435/bash-string-compare-to-multiple-correct-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!