linux

Iterate through the output of a shell command using a for loop

Using a for loop, you can iterate through the output of a command like ls or find.

In the example below, I've written a for loop along with the ls command and placed it in a shell file named test.sh

#!/bin/sh

COUNT=0;
for FILENAME in `ls`
do
    COUNT=$((COUNT+1))
    echo "$COUNT $FILENAME"
done

running this file lists the contents of the current working directory, along with the current iteration.

$ ./test.sh
1 Mustache
2 test.sh

more bash posts

more Linux posts