Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a script with a for loop by sudo command

I was making a script, when I found a problem with sudo command and for loop.

I have this test script

for i in {0..10..2}
do
    echo "Welcome $i times"
done

Normal output should be this:

Welcome 0 times
Welcome 2 times
Welcome 4 times
Welcome 6 times
Welcome 8 times
Welcome 10 times

But it shows this:Welcome {0..10..2} times any ideas ?

bash version:4.3.11(1)-release

like image 455
Jakub Doležal Avatar asked Jun 27 '15 16:06

Jakub Doležal


2 Answers

The shell in sudo does not do brace expansion.

$ cat s.sh 
echo $SHELL
echo $SHELLOPTS
for i in {0..10..2}
      do
        echo "Welcome $i times"
      done

$ ./s.sh
/bin/bash
braceexpand:hashall:interactive-comments
Welcome 0 times
Welcome 2 times
Welcome 4 times
Welcome 6 times
Welcome 8 times
Welcome 10 times

$ sudo ./s.sh
/bin/bash

Welcome {0..10..2} times

Use seq() as others have suggested.

like image 159
Nathan Wilson Avatar answered Oct 03 '22 07:10

Nathan Wilson


The {0..10..2} syntax is only supported in Bash 4.

For Bash 3, use this syntax instead:

$ for ((i=0; i<=10; i+=2)); do echo "Welcome $i times"; done
Welcome 0 times
Welcome 2 times
Welcome 4 times
Welcome 6 times
Welcome 8 times
Welcome 10 times

You can see what is happening in Bash 3.2 if you remove the step part of the brace expansion:

bash-3.2$ for i in {0..10..2}; do echo "i=>$i"; done
i=>{0..10..2}
bash-3.2$ for i in {0..10}; do echo "i=>$i"; done
i=>0
i=>1
i=>2
i=>3
i=>4
i=>5
i=>6
i=>7
i=>8
i=>9
i=>10

BUT on Bash 4, it works as you desired it to:

bash-4.3$ for i in {0..10..2}; do echo "i=>$i"; done
i=>0
i=>2
i=>4
i=>6
i=>8
i=>10

Edit

As Nathan Wilson correctly points out, this is probably the result of the Bash option braceexpand being negative.

You can set this value with set:

$ echo $SHELLOPTS
braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor:posix
$ for i in {0..5}; do echo "i=>$i"; done
i=>0
i=>1
i=>2
i=>3
i=>4
i=>5
$ set +B
$ echo $SHELLOPTS
emacs:hashall:histexpand:history:interactive-comments:monitor:posix
$ for i in {0..5}; do echo "i=>$i"; done
i=>{0..5}
like image 31
dawg Avatar answered Oct 03 '22 08:10

dawg