- Linux Admin Tutorial
- Home
- CentOS Overview
- Basic CentOS Linux Commands
- File / Folder Management
- User Management
- Quota Management
- Systemd Services Start and Stop
- Resource Mgmt with systemctl
- Resource Mgmt with crgoups
- Process Management
- Firewall Setup
- Configure PHP in CentOS Linux
- Set Up Python with CentOS Linux
- Configure Ruby on CentOS Linux
- Set Up Perl for CentOS Linux
- Install and Configure Open LDAP
- Create SSL Certificates
- Install Apache Web Server CentOS 7
- MySQL Setup On CentOS 7
- Set Up Postfix MTA and IMAP/POP3
- Install Anonymous FTP
- Remote Management
- Traffic Monitoring in CentOS
- Log Management
- Backup and Recovery
- System Updates
- Shell Scripting
- Package Management
- Volume Management
- Linux Admin Useful Resources
- Linux Admin - Quick Guide
- Linux Admin - Useful Resources
- Linux Admin - Discussion
Linux Admin - Loops
Like all other programming languages BASH makes use of common looping structures − for, while, and until.
for loop
The for loop is used to execute other shell instructions repeatedly. The for loop is classified as an iteration statement in BASH.
#!/bin/bash myFile = "myLines.txt" for i in `cat $myFile` do echo $i done
The above for loop iterates through the contents of *myLines.txt" and echoes each line to the terminal.
Note − When a command is enclosed in backticks (shift+tilde) the command's output will be assigned to a variable.
while loop
This loop will execute until a condition is satisfied. We saw this used previously with the shell routine that repeatedly echoed and incremented.
Let's read a file with the while loop −
#!/bin/bash myFile = "myLines.txt" while read -a FILELINE; do echo $FILELINE done < $myFile
Again, this small script displays the contents of our text file.
Note − The first line of your script should always contain the shebang line. This is simply the path to your BASH shell interpreter. Usually, located in /bin/bash on CentOS.
until loop
The until loop is similar in syntax to the while loop. The difference is, the until loop will execute until a command executes successfully.
With that in mind, we'd just need to negate our while script to execute with until
#!/bin/bash myFile = "myLines.txt" until ! read -a FILELINE; do echo $FILELINE done < $myFile