Looping over output of 'ls'

Hi,

I have some output from 'ls' command and I want to loop over the output in a bash script. What would be a good way to go about it?

For example, if the output of the ls command gives me 'prefix1 prefix2 prefix3', how can I set a loop that will iterate over these?

many thanks!

#looper.sh
#while (( 1 ))
do
        ${2}
        echo "--------------------------"
        sleep ${1}
done 
./looper.sh 30 "ls -l"

ctrl-C to stop

for i in `ls`; do <desired_command> $i; done

Not necessary to use ls:

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

It's also not necessary to quote your $i element.

$i should be wrapped in double quotes to avoid field splitting or other interpretations by the shell. If there are files with spaces for example, they will break your script..

1 Like