Bash Scripting: Difference between revisions
| Line 78: | Line 78: | ||
fi | fi | ||
IFS='' # To preserve any existing spacing. | |||
while read i ; do echo -e "${Prepend}$i" ; done | while read i ; do echo -e "${Prepend}$i" ; done | ||
} | } | ||
Revision as of 19:05, 8 April 2015
Common Functions
Here are some common functions I use in my scripts.
Prompt
You can prompt the user for an yes or no answer using this function. An optional default values are accepted as the second argument.
Example Usage:
if prompt "Is this okay?" Y ; then
echo "It's Okay!"
fi
if ! prompt "Is this okay?" N ; then
echo "It's not okay!"
fi
Function:
function prompt() {
# credit: http://djm.me/ask
while true; do
if [ "${2:-}" = "Y" ]; then
prompt="Y/n"
default=Y
elif [ "${2:-}" = "N" ]; then
prompt="y/N"
default=N
else
prompt="y/n"
default=
fi
# Ask the question
read -p "$1 [$prompt] " REPLY
# Default?
if [ -z "$REPLY" ]; then
REPLY=$default
fi
# Check if the reply is valid
case "$REPLY" in
Y*|y*) return 0 ;;
N*|n*) return 1 ;;
esac
done
}
die
Similar to the die command in PHP which prints out a message before stopping execution.
Function:
function die {
echo $@
exit
}
The caveat is that exit will kill the current shell - if running in a subshell, this will terminate the subshell and not the parent shell. To get around this, you may need to kill the parent PID instead.
Indent
Indents text piped to the function.
Function:
function Indent {
Prepend="\t"
if [ $# -eq 1 ] ; then
Indent=$1
while [ $Indent -ge 0 ] ; do
Prepend="\t$Prepend"
Indent=$(($Indent - 1))
done
fi
IFS='' # To preserve any existing spacing.
while read i ; do echo -e "${Prepend}$i" ; done
}
Usage:
echo "test" | Indent
test
echo "test" | Indent 2
test
Extracting / Parsing Filenames
Use the basename to extract filenames from a path and and dirname to extract the path of a filename.
Eg:
dirname /etc/hosts /etc
basename /etc/hosts hosts
To extract only the extension or the filename without the extension, use bash's string matching:
Filename=$(basename /etc/resolv.conf)
Ext="${Filename##*.}"
Name="${Filename%.*}"
Arithmetic Operations
Do integer arithmetic operations on variables within double brackets. For example:
Value=1 ValuePlusOne=$((Value + 1)) ValueTimes12=$((Value * 12))
The operators that are supported are:
+ - / * %
Bitwise operators also work:
^ (XOR) | (OR) & (AND)
Control Blocks
Switch
read -p "What do you want to do?: " Option
case "$Option" in
"K")
install_new_kernel
die "Complete!"
;;
"H")
usage
;;
*)
die "Stopping installation."
;;
esac
Snippets
Get First IP Address
ip a | /bin/grep inet | grep -v inet6 | tail -n+2 | head -n 1 | awk '{print $2}' | cut -d'/' -f1