1

I've a file new.sh

i=5
i=$[i+1]
echo $i

when I execute ./new.sh, it shows 6. But when I execute "sh new.sh", it shows

$[i+1]

as output. I just want to know why, and I need a code which will work on both.

3 Answers 3

1

Many Linux distributions use dash as their standard shell for scripts and therefore /bin/sh is only a symlink to /bin/dash, which is more lightweight, but lags some functionality compared with bash. Check that with:

ls -l /bin/sh

If you want to write POSIX compatible scripts, you should use foo=$n; $((n=n+1)) instead of foo=$((n++)) and foo=$((n=n+1)) instead of foo=$((++n)). The form $[] is deprecated and should be avoided.

0
0

The OS decides what type of file it is based on the first line. Make it:

#!/bin/bash
1
0

The behaviour is different because when bash is run as sh, it turns off bash-specific features and hews more closely to the POSIX shell standard.

If you want your code to work the same under both bash and sh, you will need to write your code in the sh subset of the bash syntax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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