How to run a script using a for loop with the sudo command

I was creating a script when I found a problem with the sudo command and for the loop.

I have this test script

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

The normal output should be as follows:

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

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

bash version: 4.3.11 (1) -release

+5
source share
4 answers

A wrapper in sudo does not perform parenthesis 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 suggested.

+4
source

The syntax {0..10..2} supported only 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 happens in Bash 3.2 if you remove the stepping part of the brace extension:

 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 please:

 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 a negative result of Bash braceexpand .

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} 
+1
source

I'm not sure if I understood you correctly, but you can use the code below to create the same output. Here is my test script

 for i in $(seq 0 5) do echo "Welcome $(( $i * 2)) times" done 

Output

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

More information about the seq command can be found here.

0
source

So the script should be as follows:

for i in $(seq 0 5) do echo "Welcome $(( $i * 2)) times" done Thank you my-thoughts .

0
source

All Articles