Bash foreach loop examples for Linux / Unix


I used foreach on a Unix operating system and csh shell loop. Now, I am a Linux operating system. How do I use foreach loop in bash shell running on Linux?

The C shell (csh) or the improved version, tcsh is a Unix shell from the late 1970s. The csh foreach loop syntax is as follows:

Linux foreach tcsh example
However, bash lacks foreach syntax; instead, you can use bash while loop or bash for loop syntax as described below.

Bash foreach loop examples

Let us say you want to convert the following csh forloop example:

Unix foreach tcsh example
Above csh or tcsh foreach displayed a list of files using loop. Here is similar code in a bash shell:

Bash foreach loop example
However, one can find and safely handle file names containing newlines, spaces, special characters using the find command

Howto use foreach in bash shell

Say you have a file named lists.txt as follows:
cat lists.txt
Sample outputs:

Each in there is a file located on your Unix or Linux server. Here is how to read lists.txt file and work on each file listed in lists.txt:

Although for loop seems easy to use for reading the file, it has some problems. Don’t try to use “for” to read file line by line in Linux or Unix. Instead, use while loop as follows:

Foreach loop in bash

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.


Facebook Comments

Show More

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button