Skip to content

Files

Latest commit

 

History

History
48 lines (32 loc) · 1.24 KB

SC2066.md

File metadata and controls

48 lines (32 loc) · 1.24 KB

Pattern: Loop with one iteration in shell script

Issue: -

Description

You get this warning because you have a loop that will only ever run exactly one iteration. Since you have a loop, you clearly expect it to run more than once. You just have to decide how it should be split up.

Example of incorrect code:

for s in "$(somecommand)"; do echo "$s"; done

Example of correct code:

The correct code depends on your intention. Let's say you're in a directory with the files file.png and My cat.png, and you want to loop over a command that outputs (or variable that contains):

hello world
My *.png

Loop over each line without globbing (hello world, My *.png)

somecommand | while IFS= read -r s; do echo "$s"; done

Loop over each word with globbing (hello, world, My, file.png, My cat.png):

# relies on the fact that IFS by default contains space-tab-linefeed
for s in $(somecommand); do echo "$s"; done

Loop over each line with globbing (hello world, My cat.png)

# explicitly set IFS to contain only a line feed
IFS='
'
for s in $(somecommand); do echo "$s"; done

Further Reading