Introduction to Bash Shell Scripting and Syntax
Introduction to Shell Scripting
A script is defined as a short program designed to perform a specific, targeted task. It consists of a series of commands combined into a single executable file.
A shell script is a script that is executed specifically by a command-line shell.
Most shells, including bash, possess a built-in syntax for writing script programs.
There is a threshold for script complexity: if a script exceeds approximately to lines of code, it is recommended to switch to a more robust programming language.
The general workflow for writing a bash script involves:
Typing one or more commands into a file and saving it.
Including a special header at the top of the file to identify the interpreter.
Enabling execute permissions on the file.
Running the file.
Basic Script Syntax and Components
The first line of an executable script must be the shebang or interpreter directive, written as
#!interpreter. This line dictates which interpreter will run the commands in the script.The standard interpreter for these scripts is
/bin/bash.Example of a basic script that removes output files and lists current files:
#!/bin/bashrm output*.txtls -l
Executing Shell Scripts
There are three primary methods to run a shell script:
Making it Executable (Recommended): Use the command
chmod u+x myscript.shand run it with./myscript.sh. This process forks a new process, executes the commands, and then exits.Launching a New Shell: Use the command
bash myscript.sh. The advantage of this method is that it can run without execute permissions, though read permissions are still required.Running Within the Current Shell: Use the command
source myscript.sh. This is advantageous because any variables defined within the script will remain available in the current shell session after execution.
Scripting Logic and Commands
The echo Command: This command produces its parameters as output, functioning similarly to
printlnin other languages.The
-nflag can be used to remove the trailing newline character, allowing it to function like a standardprintstatement.
Exercise: Write a script for the attu system that clears the screen, displays the date and time, and shows currently logged-on users along with processor info.
Script Example Implementation:
#!/bin/bashclearecho "Today's date is $(date)"echoecho "These users are currently connected:"w -h | sortechoecho "This is $(uname -s) on a $(uname -m) processor."echoecho "This is the uptime information:"uptimeechoecho "That's all folks!"
Shell Comments
Bash supports only single-line comments using the
#symbol. There is no equivalent to multi-line comment blocks like/* ... */seen in other languages.Example of comments in usage:
#!/bin/bash# Leonard's first script ever# by Leonard Linuxecho "This is my amazing script!"echo "The time is: $(date)" # This is the part where I print my current directoryecho "Current dir is:prefix before the name.Example:
echo "$NAME is $AGE years old"outputsMichael Young is 64 years old.
Common Errors in Variable Management
Misspelling: If a variable name is misspelled during assignment (e.g.,
Name=Robinstead ofNAME=Rob), bash will simply create a new variable rather than updating the intended one.Undeclared Variables: Using a variable that has not been defined results in an empty value rather than an error (e.g.,
echo "Welcome, $name"results inWelcome,).Multi-word Strings: When storing strings containing spaces, double quotes must be used.
NAME=Ruth Andersonwill fail, whileNAME="Ruth Anderson"correctly assigns the value.The $ Prefix during Assignment: Using the
$symbol when assigning or reassigning a variable is an error.is incorrect; only use the name for the target of an assignment.Forgetting echo: If you type
$nameinstead ofecho $name, the shell will attempt to execute the value of the variable as a command.
Command Output Capture and Quotation Mechanics
Output from a command can be captured into a variable using the syntax
variable=(ls *.txt).Complex example:
FILE=()are executed.Example:
"Hi $NAME! Today is $(date)"expands to include the variable value and current date.
Single Quotes: These treat all characters literally. Variables are not expanded, and commands in
$()are not performed.Example:
'Hi $NAME! Today is x + $y"results in.Supported integer operators include addition
+, subtraction-, multiplication*, division/, and modulo%.The
bccommand can be utilized for more complex mathematical expressions.If a non-numeric variable is used in a numeric context (via
let), its value is treated as .
Comparison with Java:
In Java,
String s = "hello";corresponds tos=helloin Bash.In Java,
System.out.println(s);corresponds toecho {s}s.Integer parsing and addition in Java
int n = Integer.parseInt(s2) + Integer.parseInt(s3);is achieved in Bash vialet n="$s2 + $s3".
Built-in Shell Variables and Environment Configuration
Several special variables are automatically defined in every bash session:
HOSTNAME: The name of the computer currently in use.PATH: A list of directories searched by the shell to find executable commands.PWD: The current working directory.USER: The current login username.
The PATH. Users can modify this to include custom script directories:
PATH=$PATH:/homes/iws/rea.
Variable Persistence and Visibility
Management Commands:
set: Displays all variables (not typically needed for assignment, asx=3suffices).unset: Deletes a variable and its associated value.export: Sets a variable and ensures it is inherited by any child processes or programs launched by the current shell.readonly: Marks a variable so it cannot be modified by programs launched from that shell.
Exercise: Setting a local variable and launching a new bash shell will show the variable is not visible unless
exportis used before launching the new shell.
Console and Command-line Input/Output
Values read from the console are always stored as strings.
Shell Commands for I/O:
read: Takes input from the console and stores it in a variable. The-pflag acts as a prompt.echo: Outputs text to the console.printf: Outputs formatted text to the console (e.g.,printf "%10s is %4s years old" $name $age).
Command-line Arguments: Accessing arguments passed when starting a script:
$0: The name of the script itself.$1, $2, #: Total number of arguments provided.@.Loop Examples:
Looping over colors:
for val in red blue green; do echo "val is: $val"; done.Looping over arguments:
for val in $@; do echo "val is: $val"; done.Using the
seqcommand:for val in $(seq 4); do echo "val is: $val"; donegenerates a sequence from to .File processing:
for file in *.txt; do mv $file ${file}2; donerenames all text files to have a.txt2extension.
Practical Application: createhw.sh
Task: Create a script named
createhw.shthat generates a series of homework directories (hw1,hw2, etc.) up to a maximum number specified by a command-line argument. Within each directory, a filecriteria.txtshould be copied and renamed tocriteria(2*i).txt, and ascript.shfile should be copied and executed.Complete Script Solution:
#!/bin/bash# Creates directories for a given number of assignments.for num in $(seq $1); dolet CRITNUM="2 * num"cp script.sh "hwnum/criterianum."cd "hw$num/"bash ./script.shcd ..done
This script demonstrates the use of command-line arguments (
$1), theseqcommand, theletcommand for arithmetic, and directory navigation within loops.