Why does my Bash for loop fail when run with bash or sudo?

0
0
Asked By MellowCedar42 On

I can run this loop directly and it lists the files in the current directory:

for i in *; do echo "$i"; done

However, trying to run it as `bash for i in *; do echo "$i"; done` produces a syntax error near `do`. I also want to run the loop through `bash -c` or as an administrator with `sudo`. What quoting or escaping is required, and why does invoking Bash this way change the behavior?

3 Answers

Answered By QuietOtter7 On

`bash for i in ...` does not treat the text as a command to interpret. Bash sees `for` as the name of a script or file and the remaining words as arguments. To pass a command string to a new Bash process, use `-c` and quote the entire loop: `bash -c 'for i in *; do echo "$i"; done'`. The quotes keep the loop together as one argument and prevent the current shell from expanding `*` first.

Answered By SilverMaple18 On

If you only want a subshell, you do not need to start another Bash process. Group the loop in parentheses: `( for i in *; do echo "$i"; done )`. This runs it in a subshell environment. Also, quote `"$i"` so filenames containing spaces or wildcard characters are handled safely.

Answered By BrightHarbor63 On

For an administrator shell, put the complete command after `sudo bash -c` and quote it as one argument: `sudo bash -c 'for i in *; do echo "$i"; done'`. Without the quotes, the outer shell splits the loop into separate arguments before Bash receives it, so the syntax is no longer a single script.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.