This is an old revision of the document!
Use Shell Scripting To Automate System Maintenance Tasks
General Information
Review of common shell scripting syntax.
General Layout
General bash script layout
#!/bin/bash echo "Hello world" exit 0
Arguments
Sending and parsing arguments to scripts.
#!/bin/bash echo "The first argument is: $1" echo "The second argument is: $2" echo "There are $# total arguments." echo "All of the arguments are: $@" # Loop through arguments one at a time for myarg in $@; do echo "Argument is: $myarg" done
Getting User Input
User input with the read command
#!/bin/bash # If there is no argument passed, prompt for input if [ -z $1 ]; then echo "Enter something: " read myname else # There is an argument, use that myname=$1 fi echo "You entered: $myname" exit 0
Conditionals
If/else conditional testing
if [ -f $1 ]; then echo "Argument is a file" elif [ -d $1 ]; then echo "Argument is a directory" else echo "Argument is something else..." fi exit 0
Logical operators
# Logical AND: If first command is true, execute second command [ -f $1 ] && echo "This is a file" # Logical OR: If first command is true, do not execute second command [ -f $1 ] || echo "This is not a file"