

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
- 1,654 Views
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
Accepted Solutions

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
- 1,629 Views
[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


- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
- 1,605 Views

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
- 1,631 Views
[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


- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
- 1,607 Views