Bash Scripting – Looping Through ls Results in Bash Shell Script

bashshellshell-script

Does any one have a template shell script for doing something with ls for a list of directory names and looping through each one and doing something?

I'm planning to do ls -1d */ to get the list of directory names.

Best Answer

Edited not to use ls where a glob would do, as @shawn-j-goff and others suggested.

Just use a for..do..done loop:

for f in *; do
  echo "File -> $f"
done

You can replace the * with *.txt or any other glob that returns a list (of files, directories, or anything for that matter), a command that generates a list, e.g., $(cat filelist.txt), or actually replace it with a list.

Within the do loop, you just refer to the loop variable with the dollar sign prefix (so $f in the above example). You can echo it or do anything else to it you want.

For example, to rename all the .xml files in the current directory to .txt:

for x in *.xml; do 
  t=$(echo $x | sed 's/\.xml$/.txt/'); 
  mv $x $t && echo "moved $x -> $t"
done

Or even better, if you are using Bash you can use Bash parameter expansions rather than spawning a subshell:

for x in *.xml; do 
  t=${x%.xml}.txt
  mv $x $t && echo "moved $x -> $t"
done
Related Question