How do I echo a sum of a variable and a number?

前端 未结 9 678
眼角桃花
眼角桃花 2020-12-30 05:03

I have a variable x=7 and I want to echo it plus one, like echo ($x+1) but I\'m getting:

bash: syntax error near unexpected

相关标签:
9条回答
  • 2020-12-30 05:30

    Try double parentheses:

    $ x=7; echo $(($x + 1))
    8
    
    0 讨论(0)
  • 2020-12-30 05:32

    try echo $(($x + 1))

    I think that only works on some version of bash that is 3 or more..

    echo `expr $x + 1`
    

    would be another solution

    0 讨论(0)
  • 2020-12-30 05:40

    Just use the expr command:

    $ expr $x + 1
    8
    
    0 讨论(0)
  • 2020-12-30 05:40

    echo $((x+1)) also same result as echo $(($x+1))

    0 讨论(0)
  • 2020-12-30 05:44
    $ echo $(($x+1))
    8
    

    From man bash:

    Arithmetic Expansion

    Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmetic expansion is:

        $((expression))
    

    The expression is treated as if it were within double quotes, but a double quote inside the parentheses is not treated specially. All tokens in the expression undergo parameter expansion, string expansion, command substitution, and quote removal. Arithmetic substitutions may be nested.

    The evaluation is performed according to the rules listed below under ARITHMETIC EVALUATION. If expression is invalid, bash prints a message indicating failure and no substitution occurs.

    0 讨论(0)
  • 2020-12-30 05:48

    No need for expr, POSIX shell allows $(( )) for arithmetic evaluation:

    echo $((x+1))
    

    See §2.6.4

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