Syntax error checking whether account number is numeric

前端 未结 2 1273
挽巷
挽巷 2021-01-29 13:17
if [[ ${account_nr} =~ ^[0-9]+$ &&  ${from_account_nr} =~ ^[0-9]+$ ]]

This is intended to check whether the account number is numeric or not. I

2条回答
  •  独厮守ぢ
    2021-01-29 13:48

    A space is required between if and [:

    $ account_num=1234
    $ if [[ ${accoun_num} =~ ^[0-9]+$ ]] ; then echo "foo" ; fi
    foo
    $
    

    Also, this works fine in bash:

    $ account_nr=1234
    $ from_account_nr=9876
    $ if [[ ${account_nr} =~ ^[0-9]+$ && ${from_account_nr} =~ ^[0-9]+$ ]] ; then echo "foo" ; fi
    foo
    $
    

    You cannot have spaces around your shell variable assignments, either. Below is a correction to your latest version:

    jai="CNM"
    hanuman="BRK"
    if [[ $jai =~ ^[0-9]+$ && $hanuman =~ ^[0-9]+$  ]]
    then
      echo "Jai hanuman"
      echo "valid input"
    fi
    

    Since neither jai or hanuman are numbers, the above script runs and outputs nothing. If you set them both to a number, then it will display:

    Jai hanuman
    valid input
    

    Note that if you put a space, like so:

    jai = "CNM"
    

    Then the shell (bash) thinks you are executing a command called jai and you get the error indicated.

提交回复
热议问题