In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article is to share with you about how to write a cycle in Bash. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article.
Use the for loop and the find command to automatically perform a set of operations on multiple files.
A common reason people want to learn about Unix shell is to release the functionality of batch processing. If you want to do something on many files, one way is to construct a command that traverses those files. In programming terms, this is called execution control, and one of the most common examples is the for loop.
The for loop is a recipe that details what you want the computer to do with each specified data object, such as a file.
* * Classic cycle *
Linux Terminal for Linux 7 Terminal Emulator 10 command-line tools for data analysis in Linux download immediately: SSH cheat sheet Advanced Linux Command cheat sheet Linux Command Line tutorial A simple loop is a loop for analyzing a collection of files. This may not be a useful loop in itself, but it is a safe way to prove to you that you are capable of working with each file in the directory separately. First, create a simple test environment by creating a directory and putting some copies of some files into it. You can use any file at first, but later examples require a graphic file (such as JPEG, PNG, or similar). You can use the File Manager or create a folder in the terminal and copy files to it:
$mkdir example$ cp ~ / Pictures/vacation/*. {png,jpg} example change the directory to a new folder and list the files in it to confirm that the test environment meets your expectations: $cd example$ ls-1cat.jpgdesign_maori.pngotago.jpgwaterfall.png
The syntax for traversing each file one by one in a loop is to create a variable. Then define the dataset that you want the variable to loop through. In this case, use wildcards to cycle through all files in the current directory (wildcards match everything). Then terminate the introductory clause with a semicolon (;).
$for f in *
According to your preference, you can choose to press here to return. Shell does not attempt to execute a loop until it is syntactically complete.
Next, define what you want to happen in each iteration of the loop. For simplicity, use the file command to get a small amount of data about each file, represented by the f variable (but starting with $, tell shell to replace the value of the variable with the currently contained variable):
Do file $f
Terminate the clause with another semicolon and close the loop:
Done
When you are done, press the Return key to start the Shell loop to traverse everything in the current directory. The for loop assigns each file to the variable f one by one, and then runs the command:
$for f in *; do > file $f; > done cat.jpg: JPEG image data, EXIF standard 2.2 design_maori.png: PNG image data, 4608 x 2592, 8-bit/color RGB, non-interlaced otago.jpg: JPEG image data, EXIF standard 2.2 waterfall.png: PNG image data, 4608 x 2592, 8-bit/color RGB, non-interlaced
You can also write:
$for f in *; do file $f; done cat.jpg: JPEG image data, EXIF standard 2.2 design_maori.png: PNG image data, 4608 x 2592, 8-bit/color RGB, non-interlaced otago.jpg: JPEG image data, EXIF standard 2.2 waterfall.png: PNG image data, 4608 x 2592, 8-bit/color RGB, non-interlaced
The multi-line and single-line formats are the same for your shell and produce exactly the same results.
* * A practical example *
This is a practical example of how loops can be useful for daily calculations. Suppose you have a collection of vacation photos to send to your friends. Your photo file is too large to be sent by email, and it is inconvenient to upload to your photo sharing service. You want to create a smaller online version of your photos, but you have 100 photos and you don't want to waste time shrinking each one.
First, install the ImageMagick command using the package manager on Linux,BSD or Mac. For example, on Fedora and RHEL:
$sudo dnf install ImageMagick
On Ubuntu or Debian:
$sudo apt install ImageMagick
On BSD, use the port or pkgsrc. On Mac, use Homebrew or MacPorts.
After installing ImageMagick, you will have a new set of commands for manipulating photos.
Create a destination directory for the file you want to create:
$mkdir tmp
To shrink each photo to 33% of its original size, try the following loop:
$for f in *; do convert $f-scale 33% tmp/$f; done
Then view the zoomed photos in the tmp folder.
You can use any number of commands in a loop, so if you need to perform complex operations on a batch of files, you can place the entire workflow between the do and done statements of the for loop. For example, suppose you want to copy each processed photo directly to a shared photo directory on your Web host and delete the photo file from 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
When you are done, your computer will automatically run three commands for each file processed by the for loop. This means that if you only deal with 10 photos in this way, you can save yourself 30 commands and the same amount of time.
* * limit loops *
You don't always have to check every file. You may only want to work with the JPEG files in the sample directory:
$for f in * .jpg; do convert $f-scale 33% tmp/$f; done$ ls-m tmpcat.jpg, otago.jpg
After completing the ls-m tmpcat.jpg,otago.jpg or, you may need to repeat the operation a certain number of times instead of processing the file. The variables of the for loop are defined by any data you provide, so you can create a loop that iterates through numbers instead of files:
$for n in {0.. 4}; do echo $n; done01234
* * more loops *
You now know enough to create your own loop. Before you are satisfied with the loop, use them on the copies of the files you want to work on, and use as many commands with built-in protections as possible to prevent you from destroying the data and causing irreparable errors, such as accidentally renaming the entire file. file directories with the same name overwrite each other.
For advanced for Loop topics, read on.
* * not all shell is Bash****
The for keyword is built into Bash shell. Many similar shell use the same keywords and syntax, but some shell (such as tcsh) use different keywords (such as foreach) instead.
In tcsh, the syntax is similar in nature, but stricter than Bash. In the following code example, do you want to not type the string foreach? In lines 2 and 3. It is an auxiliary reminder 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 separate lines, so you can't create a for loop on a line like you did with Bash and similar shell.
* * use find command to execute for loop *
In theory, you may find a shell that does not provide a for loop function, or you may just prefer to use other commands with additional functionality.
The find command is another way to implement the for loop function because it provides several ways to define the range of files to be included in the loop and parallel processing options.
The find command is designed to help you find files on your hard drive. Its syntax is simple: you provide the path to the location you want to search and find all files and directories:
$find... / cat.jpg./design_maori.png./otago.jpg./waterfall.png
You can filter search results by adding a portion of name:
$find. -name "* jpg". / cat.jpg./otago.jpg
The advantage of find is that you can enter every file you find into a loop using the-exec flag. For example, to shrink only the PNG photos in the sample directory:
$find. -name "* png"-exec convert {}-scale 33% tmp/ {}\; $ls-m tmpdesign_maori.png, waterfall.png
In the-exec clause, the parenthesis character {} represents any item being processed (in other words, any PNG-terminated file that has been located, one at a time). The-exec clause must end with a semicolon, but Bash usually tries to use a semicolon on its own. Use the backslash (;) "escape" semicolon so that find knows to treat the semicolon as its termination character.
The find command is very good at its functionality, and sometimes it can be too good. For example, if you reuse it to find another photo-processed PNG file, there will be some errors:
$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 found all the PNG files-not just the current directory (. Also includes files that you previously processed and placed in the tmp subdirectory In some cases, you may want to search the current directory and all other directories in it (and all directories in it). It can be a powerful recursive processing tool, especially in complex file structures (for example, music artists' directories contain albums full of music files), but you can restrict them with the-maxdepth option.
Find only the PNG files in the current directory (excluding subdirectories):
$find. -maxdepth 1-name "* png"
To find and process files at the current directory and other subdirectory levels, increase the maximum depth by 1:
$find. -maxdepth 2-name "* png"
Its default value is to enter all subdirectories.
Small extension
The more times you use loops, the more time and effort you will save, and the more tasks you can handle. You are just a user, but after a thoughtful cycle, you can make the computer do the hard work.
You can and should treat the loop like any other command so that you can keep it handy when you need to repeat one or two operations on multiple files. However, it is also a legitimate way to program carefully, so if you have to perform complex tasks on any number of files, take some time to plan your workflow. If you can achieve your goal on a file, it is relatively simple to wrap the repeatable process in a for loop, and the only "programming" required is to understand how variables work and are organized enough to separate unprocessed files from processed files. With a few exercises, you can move from a Linux user to a Linux user who knows how to write loops!
The above is how to write a loop in Bash. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
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.