cancel
Showing results for 
Search instead for 
Did you mean: 
jeesshnasree
Starfighter Starfighter
Starfighter
  • 531 Views

sudo is not working before for loop in non-root user id

Jump to solution

Hi All,

 

How execute command with sudo in non-root user ID with for command .

 

Example:(Non-root user ID):

sudo for .....

-bash : syntax error near unexpected token 'do'

 

Please provide me command , how to execute for loop with sudo in non-root user ID. 

 

I am waiting for your valueable information .

 

Regards,

Jeesshnasree

2 Solutions

Accepted Solutions
shashi01
Moderator
Moderator
  • 506 Views

Hi @jeesshnasree 

[susan@cyber ~] sudo for i in {1..5}; do echo "test $i"; done

-bash: syntax error near unexpected token `do'

You will encounter a syntax error because sudo expects a single command, not a complex shell construct like a for loop.

===================================================================================

vim test_script.sh ## Add the for loop code to the script: ##

#!/bin/bash

for i in {1..5}; do
echo "test $i"
done

chmod +x test_script.sh

sudo ./test_script.sh
test 1
test 2
test 3
test 4
test 5

OR

(The main point to remember is that you should use sudo for each command inside the loop, rather than trying to use it for the entire loop. Another good method is to put the loop in a script file and run that script with sudo.)

for i in {1..5}; do sudo echo "test $i"; done

View solution in original post

jeesshnasree
Starfighter Starfighter
Starfighter
  • 482 Views

Hi @shashi01 ,

 

Thank you , it is working .

View solution in original post

0 Kudos
2 Replies
shashi01
Moderator
Moderator
  • 507 Views

Hi @jeesshnasree 

[susan@cyber ~] sudo for i in {1..5}; do echo "test $i"; done

-bash: syntax error near unexpected token `do'

You will encounter a syntax error because sudo expects a single command, not a complex shell construct like a for loop.

===================================================================================

vim test_script.sh ## Add the for loop code to the script: ##

#!/bin/bash

for i in {1..5}; do
echo "test $i"
done

chmod +x test_script.sh

sudo ./test_script.sh
test 1
test 2
test 3
test 4
test 5

OR

(The main point to remember is that you should use sudo for each command inside the loop, rather than trying to use it for the entire loop. Another good method is to put the loop in a script file and run that script with sudo.)

for i in {1..5}; do sudo echo "test $i"; done

jeesshnasree
Starfighter Starfighter
Starfighter
  • 483 Views

Hi @shashi01 ,

 

Thank you , it is working .

0 Kudos
Join the discussion
You must log in to join this conversation.