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?
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?
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))
sh
syntax: age=$((age + 1))
, or : "$((age += 1))"
– Stéphane Chazelas
May 16 '19 at 18:46
./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
Another old time answer (or highly multiple platform compatible) is:
age=`expr $age + 1`
echo $SHELL
as non-root and as root ? – Httqm May 16 '19 at 15:22./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