- HowTo: Use bash For Loop In One Line
- Run Command 5 Times
- Work On Files
- Bash While Loop Examples
- bash while loop syntax
- Redirecting user input for a while Loop
- How do I use while as infinite loops ?
- Conditional while loop exit with break statement
- Early continuation with the continue statement
- Recommended readings
- How to write a loop in Bash
- Automatically perform a set of actions on multiple files with for loops and find commands.
- Subscribe now
- The classic for loop
- A practical example
- Limiting your loop
- More looping
- Not all shells are Bash
- For loops with the find command
- Looping for fun and profit
HowTo: Use bash For Loop In One Line
H ow do I use bash for loop in one line under UNIX or Linux operating systems?
The syntax is as follows to run for loop from the command prompt.
Run Command 5 Times
Work On Files
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
OK, but how do I run two commands in the for loop? for () command1; command; done
.
two commands:
for i in (); do echo $i ; ls $i; done
for i in <0..3>; do for j in <0..9>; do echo -n \($i, $j\); echo Is today the $i$j \?; done; done
I’d suggest you add an example of this to https://www.cyberciti.biz/faq/bash-for-loop/ also that would have helped me…maybe with a ToC at the top as well 🙂
Thanks for this.
For the very rare case yout got file names with a leading dash:
for i in *; do echo $i; done [ will not show files with leading dash ]
for i in “*”; do echo $i; done [ will show files with leading dash (but not one file per line) ]
Work on Folders:
for i in */; do (cd “$i” && git fetch) done
Thanks for this!
It saved me hours of banging my head on the table
thanks
Hi, I’m new in bash, please help me somebody. ..
I have one folder in linux server and in folder has some *.sql file, so I want to execute all the sql in my mysql sequencely one by one. We also want output on my display as well as in log file for every files execution error. Ex. /root/desktop/sql/1_ff_f_update. And 2_*, 3_* so on. Count of the file was change every time so we can not tell u of count of the files….
If possible help me..
Thanks in advance. .
Источник
Bash While Loop Examples
H ow do I use bash while loop to repeat specific task under Linux / UNIX operating system? How do I set infinite loops using while statement? Can you provide me the while loop examples?
The bash while loop is a control flow statement that allows code or commands to be executed repeatedly based on a given condition. For example, run echo command 5 times or read text file line by line or evaluate the options passed on the command line for a script.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | BASH or KSH on Linux/Unix-like systems |
Est. reading time | 1 minute |
bash while loop syntax
The syntax is as follows:
command1 to command3 will be executed repeatedly till condition is true. The argument for a while loop can be any boolean expression. Infinite loops occur when the conditional never evaluates to false. Here is the while loop one-liner syntax:
For example following while loop will print welcome 5 times on screen:
And here is above code as a bash while one liner:
x=1; while [ $x -le 5 ]; do echo «Welcome $x times» $(( x++ )); done
Here is a sample shell code to calculate factorial using while loop:
To run just type:
$ chmod +x script.sh
$ ./script.sh 5
The while loop in action on my Ubuntu Linux desktop
You can easily evaluate the options passed on the command line for a script using while loop:
Redirecting user input for a while Loop
How about reading user input from a file? Say you have a file as follows with various IP address:
cat bad-guys.ips.txt
List of crackers IP address:
Here is a bash while loop that read those IP address separated by Internal Field Separator ( $IFS ) to an octothorpe ( # ):
Click to enlarge
How do I use while as infinite loops ?
Infinite for while can be created with empty expressions, such as:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Conditional while loop exit with break statement
You can do early exit with the break statement inside the whil loop. You can exit from within a WHILE using break. General break statement inside the while loop is as follows:
In this example, the break statement will skip the while loop when user enters -1, otherwise it will keep adding two numbers:
Early continuation with the continue statement
To resume the next iteration of the enclosing WHILE loop use the continue statement as follows:
Recommended readings
We learned that bash while loop executes while a condition is true. See the following resource
- See all sample shell script in our bash shell directory
- Bash loops from our Linux shell scripting tutorial guide
- man bash
- help while
- help <
- help break
- help continue
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
Nice to see the Bash shell,
How do you break out of a loop
is there a break statement, or do you have to use a goto?
Yes there is a break and continue statement. man bash has more information.
Very useful examples, thank you!
Thank you so much .
you define very nicly all exampls regarding while loop secquence
statement….
could u please give the shell script for printing the fibonocci series and to know if the number is palindrome and also if it an armstrong number
Does anyone know how to write a script that echoes three different arguments three times using a loop
shift command to traverse through arguments
does anyone can give an example of a while loop within a loop?
The script “test” should set variable “filter_mode” to FALSE if there are no lines in the file “switches” and to TRUE if there exists at least one line in the file “switches”.
Why do I get “filter_mode : FALSE” eventually?
$ cat test
And my script:
Run as:
gg@GeorgSimon:
$ cat switches
switch
gg@GeorgSimon:
$ sh test
switch : switch
filter_mode : TRUE
filter_mode : FALSE
how to write a program in bash for displaying table using until statement? table should be like
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
plz reply soon….thanks
Источник
How to write a loop in Bash
Automatically perform a set of actions on multiple files with for loops and find commands.
Subscribe now
Get the highlights in your inbox every week.
A common reason people want to learn the Unix shell is to unlock the power of batch processing. If you want to perform some set of actions on many files, one of the ways to do that is by constructing a command that iterates over those files. In programming terminology, this is called execution control, and one of the most common examples of it is the for loop.
A for loop is a recipe detailing what actions you want your computer to take for each data object (such as a file) you specify.
The classic for loop
Change directory to your new folder, then list the files in it to confirm that your test environment is what you expect:
The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything). Then terminate this introductory clause with a semicolon (;).
Depending on your preference, you can choose to press Return here. The shell won’t try to execute the loop until it is syntactically complete.
Next, define what you want to happen with each iteration of the loop. For simplicity, use the file command to get a little bit of data about each file, represented by the f variable (but prepended with a $ to tell the shell to swap out the value of the variable for whatever the variable currently contains):
Terminate the clause with another semi-colon and close the loop:
Press Return to start the shell cycling through everything in the current directory. The for loop assigns each file, one by one, to the variable f and runs your command:
You can also write it this way:
Both the multi-line and single-line formats are the same to your shell and produce the exact same results.
A practical example
Here’s a practical example of how a loop can be useful for everyday computing. Assume you have a collection of vacation photos you want to send to friends. Your photo files are huge, making them too large to email and inconvenient to upload to your photo-sharing service. You want to create smaller web-versions of your photos, but you have 100 photos and don’t want to spend the time reducing each photo, one by one.
First, install the ImageMagick command using your package manager on Linux, BSD, or Mac. For instance, on Fedora and RHEL:
On Ubuntu or Debian:
On BSD, use ports or pkgsrc. On Mac, use Homebrew or MacPorts.
Once you install ImageMagick, you have a set of new commands to operate on photos.
Create a destination directory for the files you’re about to create:
To reduce each photo to 33% of its original size, try this loop:
Then look in the tmp folder to see your scaled photos.
You can use any number of commands within a loop, so if you need to perform complex actions on a batch of files, you can place your whole workflow between the do and done statements of a for loop. For example, suppose you want to copy each processed photo straight to a shared photo directory on your web host and remove the photo file from your local system:
For each file processed by the for loop, your computer automatically runs three commands. This means if you process just 10 photos this way, you save yourself 30 commands and probably at least as many minutes.
Limiting your loop
A loop doesn’t always have to look at every file. You might want to process only the JPEG files in your example directory:
Or, instead of processing files, you may need to repeat an action a specific number of times. A for loop’s variable is defined by whatever data you provide it, so you can create a loop that iterates over numbers instead of files:
More looping
You now know enough to create your own loops. Until you’re comfortable with looping, use them on copies of the files you want to process and, as often as possible, use commands with built-in safeguards to prevent you from clobbering your data and making irreparable mistakes, like accidentally renaming an entire directory of files to the same name, each overwriting the other.
For advanced for loop topics, read on.
Not all shells are Bash
The for keyword is built into the Bash shell. Many similar shells use the same keyword and syntax, but some shells, like tcsh, use a different keyword, like foreach, instead.
In tcsh, the syntax is similar in spirit but more strict than Bash. In the following code sample, do not type the string foreach? in lines 2 and 3. It is a secondary prompt alerting you that you are still in the process of building your loop.
In tcsh, both foreach and end must appear alone on separate lines, so you cannot create a for loop on one line as you can with Bash and similar shells.
For loops with the find command
In theory, you could find a shell that doesn’t provide a for loop function, or you may just prefer to use a different command with added features.
The find command is another way to implement the functionality of a for loop, as it offers several ways to define the scope of which files to include in your loop as well as options for Parallel processing.
The find command is meant to help you find files on your hard drives. Its syntax is simple: you provide the path of the location you want to search, and find finds all files and directories:
You can filter the search results by adding some portion of the name:
The great thing about find is that each file it finds can be fed into a loop using the -exec flag. For instance, to scale down only the PNG photos in your example directory:
In the -exec clause, the bracket characters <> stand in for whatever item find is processing (in other words, any file ending in PNG that has been located, one at a time). The -exec clause must be terminated with a semicolon, but Bash usually tries to use the semicolon for itself. You «escape» the semicolon with a backslash (\;) so that find knows to treat that semicolon as its terminating character.
The find command is very good at what it does, and it can be too good sometimes. For instance, if you reuse it to find PNG files for another photo process, you will get a few errors:
It seems that find has located all the PNG files—not only the ones in your current directory (.) but also those that you processed before and placed in your tmp subdirectory. In some cases, you may want find to search the current directory plus all other directories within it (and all directories in those). It can be a powerful recursive processing tool, especially in complex file structures (like directories of music artists containing directories of albums filled with music files), but you can limit this with the -maxdepth option.
To find only PNG files in the current directory (excluding subdirectories):
To find and process files in the current directory plus an additional level of subdirectories, increment the maximum depth by 1:
Its default is to descend into all subdirectories.
Looping for fun and profit
The more you use loops, the more time and effort you save, and the bigger the tasks you can tackle. You’re just one user, but with a well-thought-out loop, you can make your computer do the hard work.
You can and should treat looping like any other command, keeping it close at hand for when you need to repeat a single action or two on several files. However, it’s also a legitimate gateway to serious programming, so if you have to accomplish a complex task on any number of files, take a moment out of your day to plan out your workflow. If you can achieve your goal on one file, then wrapping that repeatable process in a for loop is relatively simple, and the only «programming» required is an understanding of how variables work and enough organization to separate unprocessed from processed files. With a little practice, you can move from a Linux user to a Linux user who knows how to write a loop, so get out there and make your computer work for you!
Источник