CT320

CT320: Network and System Administration

Fall 2015

Bash

See this page as a slide show

CHAPTER 2: Scripting and the Shell

Linux Scripting

Linux Commands

Directory Navigation

File Related

Protection Related

Process Related

System Related

Linux Shells

Redirection

Pipes

Shell Features

Filter Commands

Shell Scripts

A shell script is a program. Therefore, it deserves all of the care that any other program should get, including, as appropriate:

Morons

Only an idiot would justify sloppy work with, “It’s only a shell script, so I didn’t bother doing …”.

Sure, if it’s a short-lived (you hope) program (whether script or not), then it may not require the full treatment. However, that decision is not determined by whether or not the program is a shell script, a Perl script, a Python script, or a C++ program.

Shell Scripting

Shell scripts are programs that:

Specific syntax that follows is for bash.

Input and Output

Variables and Quoting

Arguments

Script Syntax

if/then/else

    # Spaces count!
    if [[ $num -eq 1 ]]
    then
	echo "Number is one"
    elif [[ $num -eq 2 ]]
    then
	echo "Number is two"
    else
	echo "Number is $num"
    fi

Comparisons

Loops

    for datafile in *.zot
    do
        echo Now processing $datafile
    done

    let max=5
    for ((i=0; i<max; i++))
    do
        echo $i
    done

Didn’t we just say that < is for strings⁉

Why not $max?

Arithmetic

Variables are strings; indicate numeric evaluation with: let a=2+2

    % alpha=1
    % beta=2             # no spaces around =
    % gamma=$alpha+$beta
    % let delta=alpha+beta
    % echo $gamma
    1+2
    % echo $delta
    3

You can also use $(()), but it’s unsightly.

Arrays

Somewhat limited, and certainly inelegant, capabilities compared to C:

    % array=(one two three)
    % echo ${array[1]}
    two
    % echo ${array[*]}
    one two three
    % echo ${#array[*]}
    3

Regular Expressions

Levels of Regular Expressions

Beware of “levels” of regular expressions.

Script Example

#! /bin/bash
#
# Go into a temporary “playpen” directory; clean it up when done.

# If we can’t execute a file in TMPDIR, then change it to somewhere executable.
script=$(mktemp -t playpen-script-XXXXXX)
chmod u=rx,go= "$script"
"$script" 2>&- || TMPDIR=~/tmp
rm -f "$script"

cd "$(mktemp -d -t playpen-XXXXXX)"	# Create temporary dir.
cp -r ~/.playpen/* . 2>&-		# Files to play with
chmod -R u+rw .				# Works even if no files got copied.
ls -lhog | grep -v '^total '		# Show what’s here.
DESIRED_PS1='¶ ' $SHELL
chmod -R u=rwx .			# Make everything removable.
cd /tmp					# Get away from temporary directory.
rm -rf ~-				# Remove previous, temporary, directory.

Resources

Modified: 2015-08-25T10:35

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