In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
This article will explain in detail how to use loops in Bash. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.
One of the common reasons people want to learn batch commands is to get the powerful capabilities of batch processing. If you want to execute some instructions on files in batches, constructing a command that can be run repeatedly on those files is one way. In programming terms, this is called execution control, and the for loop is one of the most common.
The for loop can describe in detail what you want the computer to do with each data object you specify, such as a file.
General cycle
A simple example of using loops is to analyze a set of files. This loop may not be useful, but it is a safe way to prove your ability to process each file in a folder independently. First, create a folder and then copy some files (such as JPEG, PNG, and so on) into the folder to generate a test environment. You can create folders and copy files through the file manager or terminal:
$mkdir example$ cp ~ / Pictures/vacation/*. {png,jpg} example
Switch to the new folder you just created, then list the files and confirm that the test environment is what you need:
$cd example$ ls-1cat.jpgdesign_maori.pngotago.jpgwaterfall.png
The syntax for iterating through files one by one in a loop is to first declare a variable (for example, using f for a file), and then define a dataset that you want to loop with variables. In this case, use the * wildcard character to traverse all files under the current folder (the wildcard character * matches all files). Then use a semicolon (;) to end the statement.
$for f in *
Depending on your personal preference, you can choose to press enter here. Shell will not attempt to execute this loop until the syntax is complete.
Next, define what you want to do in each loop. For simplicity, use the file command to get various information about the file stored in the f variable (using $to tell shell to use the value of this variable, no matter what the variable now stores):
Do file $f
End the line with another semicolon, and then close the loop:
Done
Press enter to start shell's traversal of everything under the current folder. The for loop will assign files to variable f one by one and execute your command:
$for f in *; do > file $f; > donecat.jpg: JPEG image data, EXIF standard 2.2design_maori.png: PNG image data, 4608 x 2592, 8-bit/color RGB, non-interlacedotago.jpg: JPEG image data, EXIF standard 2.2waterfall.png: PNG image data, 4608 x 2592, 8-bit/color RGB, non-interlaced
You can also write commands in this form:
$for f in *; do file $f; donecat.jpg: JPEG image data, EXIF standard 2.2design_maori.png: PNG image data, 4608 x 2592, 8-bit/color RGB, non-interlacedotago.jpg: JPEG image data, EXIF standard 2.2waterfall.png: PNG image data, 4608 x 2592, 8-bit/color RGB, non-interlaced
For your shell, there is no difference between multi-line and single-line formats, and will output exactly the same result.
A practical example
The following is a practical example of a loop in daily use. Suppose you have a bunch of holiday photos you want to send to your friends. But your photo is too big to be sent by email, and it's not convenient to upload it to a photo-sharing service. So you want to create a small web version of your photos, but you don't want to spend too much time on a compressed image volume.
First, install the ImageMagick command on your Linux, BSD, or Mac using the package manager. For example, on Fedora and RHEL:
$sudo dnf install ImageMagick
On Ubuntu and Debian:
$sudo apt install ImageMagick
On BSD, install using ports or pkgsrc. On Mac, install using Homebrew or MacPorts.
After you install ImageMagick, you have a series of new commands that you can use to manipulate images.
Create a destination folder for the files you are about to create:
$mkdir tmp
Use the loop below to reduce each picture to 33% of its original size.
$for f in *; do convert $f-scale 33% tmp/$f; done
Then you can see the scaled-down photos in the tmp folder.
You can use any number of commands in the body of the loop, so if you need to perform complex operations on a batch of files, you can put your commands between the do and done statements of a for loop. For example, suppose you want to copy all processed images to the pictures folder hosted by your website and remove these files on your local system:
$for f in *; do convert $f-scale 33% tmp/$f scp-I seth_web tmp/$f seth@example.com:~/public_html trash tmp/$f; done
Your computer will automatically execute three commands for each file processed in the for loop. This means that if you only deal with 10 images, it will save you 30 instructions and more time.
Limit your cycle
A loop often does not need to process all files. In the sample folder, all you may need to deal with is the JPEG file:
$for f in * .jpg; do convert $f-scale 33% tmp/$f; done$ ls-m tmpcat.jpg, otago.jpg
Or you want to repeat an operation a certain number of times instead of just processing files. The value of a variable in a for loop is determined by the (regardless of type) data you assign to it, so you can create a loop traversal number instead of just a file:
$for n in {0.. 4}; do echo $n; done01234 more loops
Now you know enough to create your own loop. Until you are familiar with loops, do as much as possible on copies of the files that need to be processed. Use built-in protection measures to prevent corruption of your own data and create unrepeatable errors, such as accidentally renaming all files in a folder to the same name, which may cause them to overwrite each other.
For further topics on the for loop, please continue to read.
Not all shell is Bash.
The keyword for is built into Bash shell. Many similar shell use the same keywords and syntax as Bash, but some shell, such as tcsh, use different keywords, such as foreach.
The syntax of tcsh is similar to that of Bash, but it is more strict. For example, in the following example, do not type foreach? on lines 2 and 3 of your terminal. It just reminds you that you are still in the process of building a loop.
$foreach f (*) foreach? File $fforeach? Endcat.jpg: JPEG image data, EXIF standard 2.2design_maori.png: PNG image data, 4608 x 2592, 8-bit/color RGB, non-interlacedotago.jpg: JPEG image data, EXIF standard 2.2waterfall.png: PNG image data, 4608 x 2592, 8-bit/color RGB, non-interlaced
In tcsh, both foreach and end must appear on a separate line. So you can't create a for loop with just one line of commands like Bash or other similar shell.
For Loop and find Command
In theory, you may use shell that doesn't support for loops, or you just prefer to use some of the features of other commands to do the same thing as loops.
Using the find command is another way to implement the for loop function. This command provides several ways to define the scope of which files are included in the loop and the options for parallel processing.
The find command, as its name implies, helps you query files stored on your hard drive. Its use is simple: provide a path to the location you want it to query, and then find will query all files and folders under that path.
$find... / cat.jpg./design_maori.png./otago.jpg./waterfall.png
You can filter search results by adding certain parts of the name:
$find. -name "* jpg". / cat.jpg./otago.jpg
The great thing about the find command is that you can put every file it queries into a loop with the-exec parameter flag. For example, only perform volume compression on PNG images stored in your example folder:
$find. -name "* png"-exec convert {}-scale 33% tmp/ {}\; $ls-m tmpdesign_maori.png, waterfall.png
In the-exec phrase, parentheses {} denote the items that find is working on (in other words, every file that ends in PNG). The-exec phrase must end with a semicolon, but semicolons are often used in Bash. To solve this ambiguity problem, your Terminator can use a backslash with a semicolon (\;) so that the find command knows that the Terminator is used to identify its own end of use.
The operation of the find command is great, and in some cases it can perform even better. For example, if you use the same command to find the PNG file in a new process, you may get some error messages:
$find. -name "* png"-exec convert {}-flip-flop tmp/ {}\; convert: unable to open image `tmp/./tmp/design_maori.png':No such file or directory @ error/blob.c/OpenBlob/2643....
It seems that find not only locates all PNG files in the current folder (.), but also includes files that have been processed and stored in tmp. In some cases, you may want find to query all files under the current folder plus its subfolders. The find command is a powerful recursive tool, especially when dealing with situations with complex file structures (such as folders full of musicians' albums), and you can also use the-maxdepth option to limit the maximum depth of recursion.
Only look for PNG files under the current folder (excluding subfolders):
$find. -maxdepth 1-name "* png"
Add 1 to the maximum depth of the previous command to find and process files under the current folder and the next subfolder:
$find. -maxdepth 2-name "* png"
The find command defaults to finding folders at each level.
The fun and benefits of the cycle
The more cycles you use, the more time and effort you can save, and the more you can handle huge tasks. Although you are only a user, you can make your computer accomplish difficult tasks by using loops.
You can and should use loops just like any other command. Use this command whenever possible when you need to process single or multiple files repeatedly. In any case, this is a programming activity that needs to be taken seriously, so if you need to complete complex tasks on some files, you should spend more time planning your workflow. If you can do your work on a file, it's relatively easy to wrap the operation in a for loop, where the only "programming" is to understand how variables work and to do enough planning to separate processed files from unprocessed files. After a period of practice, you can upgrade from a Linux user to a Linux user who knows how to use loops, so start making the computer work for you!
This is the end of this article on "how to use loops in Bash". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.