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?

  • 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 at 15:22
  • its /bin/bash both as normal user and as root. But Jesse answered. – Hermann Ingjaldsson May 16 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. – Isaac May 16 at 19:21
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))
  • 4
    Or use the standard sh syntax: age=$((age + 1)), or : "$((age += 1))" – Stéphane Chazelas May 16 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. – Isaac May 16 at 19:19
1

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

 age=`expr $age + 1`

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.