5

I make bash script temp.sh with the following content:

age=0;
((age++));

When I run it as a normal user, it runs fine.

But when i run it as root I get error:

./temp.sh: 4: ./temp.sh: age++: not found

Why is that?

john-jones
  • 1,736
  • Are you using the same shell and settings for both users ? What's the output of echo $SHELL as non-root and as root ? – Httqm May 16 '19 at 15:22
  • its /bin/bash both as normal user and as root. But Jesse answered. – john-jones May 16 '19 at 17:00
  • The exact output of ./temp.sh: 4: ./temp.sh: age++: not found is generated by dash running an script called as ./temp.sh. That seems to be your root shell. –  May 16 '19 at 19:21

2 Answers2

12

In the absence of a hashbang, /bin/sh is likely being used. Some POSIX shells do support the ++ and -- operators, and ((...)) for arithmetic evaluations, but are not required to.

Since you have not included a hashbang in your example I will assume you are not using one and therefore your script is likely running in a POSIX shell that does not support said operator. Such a shell would interpret ((age++)) as the age++ command being run inside two nested sub-shells.

When you run it as a "normal" user it is likely being interpreted by bash or another shell that does support said operator and ((...)).

Related: Which shell interpreter runs a script with no shebang?

To fix this you can add a hashbang to your script:

#!/bin/bash
age=0
((age++))

Note: You do not need to terminate lines with ; in bash/shell.


To make your script portable to all POSIX shells you can use the following syntax:

age=$((age + 1))
age=$((age += 1))
jesse_b
  • 37,005
  • 4
    Or use the standard sh syntax: age=$((age + 1)), or : "$((age += 1))" – Stéphane Chazelas May 16 '19 at 18:46
  • 2
    The exact output of ./temp.sh: 4: ./temp.sh: age++: not found is generated by dash running an script called as ./temp.sh. That seems to be the root shell. –  May 16 '19 at 19:19
1

Another old time answer (or highly multiple platform compatible) is:

 age=`expr $age + 1`
mdpc
  • 6,834