CS155

CS155: Introduction to Unix

Fall 2017

Shell Loops

See this page as a slide show

Shell Loops

CS155 ShellLoops

Control Flow: Repeated Execution

Simple for loop

    % cat beatles
    #! /bin/bash

    drummer="Ringo"
    for musician in John Paul George $drummer
    do
        echo "$musician was great!"
    done

    % ./beatles
    John was great!
    Paul was great!
    George was great!
    Ringo was great!

Examples

Show the contents of several files:

#! /bin/bash
cat $*

Examples

Show the contents of several files, with titles:

#! /bin/bash
for victim in "$@"
do
    echo "*** $victim"
    cat $victim
done

Remember, "$@" is the same as "$1" "$2" "$3"

Examples

The same, but add a file number to each line:

#! /bin/bash
let n=0
for victim in "$@"
do
    let n=n+1
    echo "*** File #$n: $victim"
    cat $victim
done

Examples

If you don’t say what to loop through, the loop will process "$@", which is "$1" "$2" "$3"

#! /bin/bash
let n=0
for victim
do
    let n=n+1
    echo "*** File #$n: $victim"
    cat $victim
done

Examples

Now with error checking!

#! /bin/bash
if [[ $# -eq 0 ]]
then
    echo "usage: $0 <filenames>"
    exit 1
fi
let n=0
for file
do
    let n=n+1
    echo "*** File #$n: $victim"
    cat $victim
done

Examples

#! /bin/bash
echo "Enter five numbers: "
let sum=0
let i=0
while [[ i -lt 5 ]]
do
    read num
    let sum=sum+num
    let i=i+1
done
echo $sum

Shell Scripts

#! /bin/bash
 
if [[ $# -eq 0 ]]
then
    echo "usage: $0 <filenames>"
    exit 1
fi

for item
do
    cp $item $item.backup
done

What does it do?

Shell Scripts

#! /bin/bash
 
if [[ $# -eq 0 ]]
then
    echo "usage: $0 <filenames>"
    exit 1
fi
 
for item
do
    if [[ -e $item ]]
    then
        cp $item $item.backup
    else
        echo "Can't back up $item--it doesn't exist"
    fi
done

Is this any better?

Modified: 2017-02-11T21:00

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building