Linux shell script
for loop FAQ: Can you share an example of a Linux shell script
for loop, for instance, to do something for every file in the current directory?
Sure. Here’s the core part of a shell script that you’ll find on any Unix, Linux, and Mac OS X computer I have ever worked on. The general process of this script is “for every file in the current directory do XYZ.”
The specific instance of the shell script shown below says, “For every JSP file in the current directory, run the
sed script named pp.sed, writing the output to a temporary file, then moving that temporary file back to the original filename”:
#!/bin/sh for i in `ls *.jsp` do echo "Editing $i ..." sed -f pp.sed < $i > $i.tmp mv $i.tmp $i done
This sample shell script actually demonstrates several different shell programming techniques:
- How to create a
forloop in a shell script.
- How to use the backtick operator to execute the
ls *.jspcommand inside another command.
- How to run
sedin a mode where it reads a file containing
sed script that I run here modifies a bunch of poorly formatted (but consistent) HTML. Here’s the link to that sed script.
Linux Bash shell script for loop example
I hope this Linux/Bash shell script
for loop example has been helpful. For more shell script
for loop examples just search this website, or look at the “Related” block on this web page.