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?

3
  • 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, 2019 at 15:22
  • its /bin/bash both as normal user and as root. But Jesse answered.
    – john-jones
    May 16, 2019 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.
    – user232326
    May 16, 2019 at 19:21

2 Answers 2

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))
2
  • 4
    Or use the standard sh syntax: age=$((age + 1)), or : "$((age += 1))" May 16, 2019 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.
    – user232326
    May 16, 2019 at 19:19
1

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

 age=`expr $age + 1`

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .