john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

Bash for loop examples files in a directory loop count

[TOC]

The for loop is a very powerful programming construct (do the same thing over and over until a condition is met).

The bash shell scripts support this but as always be careful of the syntax!

for loop over a list of files in a directory

1
2
3
4
#!/bin/bash
for svc in mysql redis php5-fpm nginx ; do
  /etc/init.d/$svc restart
done

explicitly name the files and do some action

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/bin/bash
# DRIVER SCRIPT to iterate over a directory of .sql files and run a script

# CURRENT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# PARENT="$(dirname "$DIR")"


SOURCE=./*             # all of the items in the current directory
DATA="data"
for FILE in $SOURCE
do
  if [ -f "$FILE" ] ;
  then
    FILENAME=${FILE##*/}       # extract after the last /
    EXTENSION=${FILENAME##*.}  # extract after the last .
    BASE=${FILENAME%.*}        # extract filename before the last .

    if [ $EXTENSION != "sh" -a $EXTENSION != "pl" ] ;
    then
      case "$BASE" in
        *data* ) echo "$BASE contains seeding Data";;
        * ) echo "$BASE defines the schema";;
      esac
    fi
  fi
done

splitting over a listing of files in a directory with the slightly trick "check if file" and "split extension"

if [ $EXTENSION = "war" ] ;
  mkdir -p $BASE
  unzip $FILENAME -d $BASE

alternate action to do on .war files, extracting each to their own subdirectory

backup a directory using a for loop

#/bin/bash
DIR=/var/lib/tomcat6/webapps/
BACKUPDIRECTORY=$DIR/BACKUP--$(/bin/date +%Y-%m-%d--%H-%M)
mkdir -p $BACKUPDIRECTORY

for d in $DIRECTORY/* ; do
  echo "Processing $d file..."
  mkdir -p $BACKUPDIRECTORY/$d
  cp -p $d/WEB-INF/app.properties $BACKUPDIRECTORY/$d/app.properties
  cp -p $d/WEB-INF/log4j.xml $BACKUPDIRECTORY/$d/log4j.xml
done

for count to 10 run a script backgrounded

1
2
3
4
5
6
7
#!/bin/bash
DIR=$(cd $(dirname "$0"); pwd)
for i in {1..10}
do
  "$DIR/GET.sh" &
  # sleep 1
done

ALLOWS THE SCRIPT TO DISCOVER WHAT DIRECTORY IT RUNS IN LOADS JOBS IN THE BACKGROUND (MULTI THREADING) , commented out the 1 second sleep

more info

http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html


  • « Rsync differential backup
  • OxygenFile »

Published

Aug 7, 2012

Category

linux

~307 words

Tags

  • bash 7
  • files 16
  • for 18
  • linux 249
  • loop 9
  • scripts 63