For loops in Bash

For loops in Bash can come in handy when for example, you want to perform bulk operations. Think of renaming all files in a directory or executing a collection of scripts. The following snippet simply iterates through a set of prime numbers and prints them to the console.

#!/bin/bash

for prime in 2 3 5 7 11 13 17 19 23 29
do
  echo $prime is a prime number
done

Result:

2 is a prime number
3 is a prime number
5 is a prime number
7 is a prime number
11 is a prime number
13 is a prime number
17 is a prime number
19 is a prime number
23 is a prime number
29 is a prime number

The next snippet lists a directory and identifies files and directories.

#!/bin/bash

LIST_DIR='/etc'

for file in `ls $LIST_DIR`
do
  if [ -f "$LIST_DIR/$file" ];
  then
    echo $LIST_DIR/$file is a file
  fi

  if [ -d "$LIST_DIR/$file" ];
  then
    echo $LIST_DIR/$file is a directory
  fi
done

Result:

/etc/6to4.conf is a file
/etc/afpovertcp.cfg is a file
/etc/aliases is a file
/etc/aliases.db is a file
/etc/amavisd.conf is a file
/etc/apache2 is a directory
/etc/asl.conf is a file
/etc/authorization is a file
/etc/auto_home is a file
/etc/auto_master is a file
...
This entry was posted in Bash and tagged , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?