Mastering Looping in Linux: A Comprehensive Guide to For Loops(linuxfor循环)

Using the for-loop in Linux is one of the most powerful ways to script and automate tasks. It is a basic programming construct which allows you to repeat a set of commands. This guide outlines the basics of how to use the for-loop in Linux, and gives several examples of how it can be applied to common tasks.

The syntax of the for-loop in Linux is simply “for var in list ; do command ; done”. ‘var’ is any name you like for a counter variable, ‘list’ can be a set of strings, numbers, paths, etc. and ‘command’ is the task you want the for-loop to perform. In addition, you can add an optional condition to the for-loop as follows: “for var in list; do command; done if condition.”

For example, let’s say you wanted to list the contents of a directory. You can use the for-loop like this:

for thing in /path/to/folder/*; do ls -l $thing; done

This loop will list the contents of the folder in long format. Alternatively, you could use a condition to list only files larger than 10MB:

for thing in /path/to/folder/*; do if [ -f $thing ] && [ $(stat -c %s $thing) -gt 10485760 ]; then ls -l $thing; fi; done

This code will list only files larger than 10MB.

Another common use of the for-loop is to iterate through a set of variables. For example, you can loop through the lines of a text file like this:

for line in $(cat some_file.txt); do echo $line; done

You can also pass multiple variables into the loop at once, which can be useful for complex tasks like copying files from one directory to another:

for files in $( ls *.jpg ); do copy $files /new/location/ done

This loop will copy all .jpg files from the current directory to the ‘new/location’ directory.

In conclusion, the for-loop in Linux is a powerful tool for automating and scripting tasks. It can be used for performing simple tasks, like listing files, or more complicated ones, like copying files or looping through variables. With a little practice, you should be able to use the for-loop with confidence and make your Linux experience a lot more efficient.


数据运维技术 » Mastering Looping in Linux: A Comprehensive Guide to For Loops(linuxfor循环)