Creating Scripts


A script is a program written in an interpreted language, typically associated with a shell or other program whose primary purpose is something other than as an interpreted language.

A shell script is a script associated with a shell used for automating shell commands.

  • is a plain text file

Creating a Shell Script

Begins with a shebang, which is a line that identifies the shell used to run the script.

  • aka hashbang, hashpling, or pound bang
  • e.g., #!/bin/bash
    • first two characters tell the Linux kernel that this is a script
    • pathname tells which program to run it
  • # is a comment
  • /bin/sh is typically a symbolic link that points to some other shell
    • usually /bin/bash
  • must make file executable when done
    • chmod +x scriptname
  • to run a script in current directory:
    • ./scriptname
    • otherwise will search the PATH
  • can move the script to directory in the PATH to run script from anywhere

Arguments

A variable is a placeholder in a script for a value that will be determined when the script runs.

  • can be
    • passed as parameters to a script
      • called parameters or arguments
      • represented by a $ followed by a number starting at 0
      • $0 is the command name itself, $1 is the first argument, and so on
      • e.g., for script myuser: useradd -m $1
        • mkuser username
    • generated internally
    • or extracted from a script’s environment
  • can assign the output of a command to a variable by setting it in backticks
    • e.g., ip=`route -n | grep UG | tr -s " " | cut -f 2 -d " "`
  • can read variables from standard input using read
    • read response reads input that is accessed with $response
    • useful for interactive scripts
    • e.g.,
echo -n "Enter a username: "
read name
user add -m $name

An environment is a set of variables that any program can access.

  • includes the current directory and the search path for running programs
  • environment variable is a special kind of variable
    • uses Bash’s export command to make the value of the variable accessible to programs launched from the shell or shell script
    • by convention, environment variables are all uppercase
    • non-environment shell script variables are lowercase or mixed case

$? is a special variable that holds the exit status (or return value) of the most recently executed command.

  • exit status is an integer value that you can check to determine whether or not the command completed correctly
    • returns 0 if program/command terminates normally
    • returns a different value to specify errors
  • can display with echo or use it in a conditional expression to perform error handling

Conditional Expressions

A conditional expression enables a script to perform one of several actions contingent on some condition.

  • multiple kinds

IF Conditional

  • if allows system to take one of two actions depending on whether some condition is true
  • syntax if [ condition ]
  • fi marks the end of an if block
  • condition appears in brackets []
    • e.g.,
      • [ -f file]
        • is true if file exists and is a regular file
      • [ -s file ]
        • is true if file exists and has a size greater than 0
      • [ string1 == string2 ]
        • is true if the two strings have the same values
  • can use test as an alternate way to specify a condition
    • e.g., if test -s /tmp/tempstuff
  • can use a commands return value as a condition
    • e.g., if [ command ]
      • executes only if the command completes successfully (no errors)
  • can expand if with else clause
if [ conditional-expression ]
	then
		command
	else
		other-commands
fi

Case Conditional

A case conditional is useful for situations where more than two outcomes are possible

  • better than nesting multiple if/then/else clauses
  • e.g.,
case word in
	pattern1) command(s) ;;
	pattern2) command(s) ;;
	...
esac
  • a word is likely to be a variable
  • each pattern is a possible value of that variable
    • can be expanded like filenames using wildcards and expansion rules
    • each must end with ;;
    • can use * as the final pattern to set a default condition
  • ends with esac

Loops

Loops are structures that tell the script to perform the same task repeatedly until some condition is met.

For Loop

  • uses the for keyword

Example

for d in `ls *.wav` ; do
	aplay $d
done
  • for loop runs once for each item generated by ls *.wav
  • each file name is assigned to $d variable

seq command generates a list of numbers starting from its first argument to its last argument.

  • e.g., seq 1 10 generates 10 lines, each with a number 1 and 10
  • can use in a for loop:
for x in `seq 1 10` ; do
	echo $x
done

While Loop

A while loop executes for as long as its condition is true.

while [ condition ]
do
	commands
done

Until Loop

An until loop executes for as long its condition is false (until it is true).

Functions

A function is a part of a script that performs a specific subtask and that can be called by name from other parts of the script.

  • defined by
    • placing parentheses after the function name
    • enclosing the lines within curly braces
myfunction() {
	commands
}
  • keyword function can optionally precede the function name

Setting an Exit Value

  • typically, a script’s exit status is the same as the last command it ran
  • can control the exit value by using exit command
    • immediately terminates the script
    • can pass a number 0-255 to return a specified exit value
      • 0 denotes success
      • 1 denotes general error