Syntax error checking whether account number is numeric

前端 未结 2 1220
挽巷
挽巷 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.

    0 讨论(0)
  • 2021-01-29 13:49

    This line is correct with advanced shells like Bash, Zsh or Ksh.

    if [[ ${account_nr} =~ ^[0-9]+$ &&  ${from_account_nr} =~ ^[0-9]+$ ]]
    

    It won't work with POSIX shells but -still- it won't show syntax error. Instead it would show that the command [[ was not found. Other causes may be related to the if statement itself but you have to show us what message was exactly shown e.g. bash: syntax error near unexpected token `fi'

    0 讨论(0)
提交回复
热议问题