25

I'm trying to write a script that will vol up radio in the background

#!/bin/sh

for (( i = 80 ; i <= 101; i++ )) 
 do 
  amixer cset numid=1 i$% sleep 60;
done 

But i have problem:

alarmclock-vol.sh: 3: alarmclock-vol.sh: Syntax error: Bad for loop variable
Kwiatkowski
  • 519
  • 2
  • 7
  • 11
  • 21
    Because [sh isn't bash](http://stackoverflow.com/questions/5725296/difference-between-sh-and-bash). `for (( … ))` is not available in sh. – kojiro May 20 '15 at 18:53
  • @kojiro: `sh` may or may not be `bash`; on some systems, `/bin/sh` is a symlink to `/bin/bash`, and the above script may work. In any case, you certainly shouldn't assume that it is. – Keith Thompson May 20 '15 at 19:14
  • 1
    @KeithThompson, though even if `sh` is a symlink to `bash`, bash behaves differently when invoked as sh (posix mode enabled). Therefore, even when sh is bash, "sh is not bash" still applies. – geirha May 20 '15 at 19:40
  • @geirha: On my Debian 6 system, `/bin/sh` is a symlink to `/bin/bash`, and the `for (( ... ))` syntax works in a script with `#!/bin/sh`; with `#!/bin/dash` it gives me `"Syntax error: Bad for loop variable"`. (It's bash 4.1.5 if that matters.) – Keith Thompson May 20 '15 at 19:47
  • @KeithThompson, yes, some syntax still works (like `for ((...))` in this case), some acts a little differently (the `source` and `.` builtins), while some syntax is disabled outright (like process substitution `<(...)` and `>(...)` ). Those are just examples that came to mind right now. – geirha May 20 '15 at 19:52

4 Answers4

35

The for (( expr ; expr ; expr )) syntax is not available in sh. Switch to bash or ksh93 if you want to use that syntax. Otherwise, the equivalent for sh is:

#!/bin/sh

i=80
while [ "$i" -le 101 ]; do
    amixer cset numid=1 "$i%"
    sleep 60
    i=$(( i + 1 ))
done 
geirha
  • 5,801
  • 1
  • 30
  • 35
  • 4
    FYI, to change to bash, change your hashbang (the first line of your script) to `#!/bin/bash` – Rob May 20 '15 at 19:50
4

use bash instead of sh

bash alarmclock-vol
Sven Eberth
  • 3,057
  • 12
  • 24
  • 29
Rishab
  • 67
  • 6
3

try using

#!/usr/bin/bash

instead of

#!/bin/bash
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 26 '21 at 04:55
3

Another way you can achieve this is by giving the file execution permission. Below are the commands:

Instead of sh filename.sh

Do this:

chmod +x filename.sh
./filename.sh

You can see in this picture

for the same code that didn't run with sh but runs after giving execution permission.

The shell script that I used here is:

#!/bin/bash
for ((i = 1; i <= 10 ; i++)); 
do
  echo $i
done