Table of Content

Weight: 4

Description: Candidates should be able to customize existing scripts, or write simple new Bash scripts.

Key Knowledge Areas:

  • Use standard sh syntax (loops, tests)
  • Use command substitution
  • Test return values for success or failure or other information provided by a command
  • Perform conditional mailing to the superuser
  • Correctly select the script interpreter through the shebang (#!) line
  • Manage the location, ownership, execution and suid-rights of scripts

Terms and Utilities:

for
while
test
if
read
seq
exec

head

#!/bin/sh

script permission

chmod a+x my-script

source

run in the current shell, as opposed to launching a new instance of the shell

$ source my-script
$ . my-script

check_interface.sh

#!/bin/sh
ip=$(route -n | grep UG | tr -s " " | cut -f 2 -d " ")
ping="bin/ping"
echo "Checking to see if $ip is up..."
$ping -c 5 $ip

add_user.sh

#!/bin/sh
echo -n "Enter a username: "
read name
useradd -m $name
passwd $name
mkdir -p /shared/$name
chown $name.users /shared/$name
chmod 775 /shared/$name
ln -s /shared/$name /home/$name/shared
chown $name.users /home/$name/shared

if

if test -s /tmp/tempstuff

if [ command ]
    then
        additional-commands
fi

if [ conditional-expression ]
    then
        commands
    else
        other-commands
fi

case word in
    pattern1) command(s) ;;
    pattern2) command(s) ;;
    ...
esac

loop

#!/bin/bash
for d in $(ls *.wav) ; do
    aplay $d
done

cp.sh 

#/bin/bash
doit() {
    cp $1 $2
}
function check() {
if [ -s $2 ]
    then
    echo "Target file exists! Exiting!"
    exit
fi
}
check $1 $2
doit $1 $2

seq

oldhorse@dclab:~$ seq --help
Usage: seq [OPTION]... LAST
  or:  seq [OPTION]... FIRST LAST
  or:  seq [OPTION]... FIRST INCREMENT LAST

oldhorse@dclab:~$ seq 1 2 6
1
3
5