Overview
• Only for light task automation, not for complex task
• For example, doing a backup
• If > 100-150 lines, use programming tool like python, pearl, ruby instead
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Prerequisites
• Pipes & Redirection
• Filtering
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Variables and Quoting
# Variable
some_number=6 # Set a variable
echo $some_number # Call a variable
# Variable
num_lines=`ls $HOME | wc -l`
echo $num_lines
10
# Quoting
# Insert a variable in a string
echo "My favorite number is $some_number"
My favorite number is 6
echo "This is my ${some_number}th beer"
This is my 6th beer
# Quoting
# Get output of a command inserted in a string
# Use backquotes ` `
echo "There are `wc -l < /etc/group` of lines in /etc/group"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
First Bash Script
which bash # locate command bash (to be put in script)
• By convention, script files are saved with file extension .sh
#!/bin/bash # must be the first line of code
# this is a comment
echo "Hello World!"
exit 0 # exit code 0 means no problem
# or
exit # use return value from last line of code
# or
exit $? # exit with the return status of the last run command
# or
exit 12 # user defined exit code
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Arguments
# Arguments reference
# file: arg.sh
$# → number of args that the script was run with
$0 → the filename of the script
$1..$n → actual script arguments
$@ → all arguments
# What's is our filename?
outfilename=$0
# How many arguments was the script called with
num_arguments=$#
# What were the arguments?
echo "The first three arguments were ${1}, ${2} and ${3}"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Run the Scripts
# Change file permission before executing the script
chmod +x arg.sh
./arg.sh hello there yo
# Output
./arg.sh
The first three arguments were hello there yo
# Run the script
# Run in the same instance of bash
./helloworld.sh
# Use a new instance of bash to run
bash helloworld.sh
# Integrate variables defined in script with the current instance
# so that you can use the variables defined in the script afterwards
source helloworld.sh
# or
. helloworld.sh
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Reload Bash Shell
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Further Reading
• Bash Quoting
• Set Index