Bash Scripting: Difference between revisions

From Leo's Notes
This page was last edited on 31 March 2015, at 18:19.
Created page with " == Extracting / Parsing Filenames == Use the <code>basename</code> to extract filenames from a path and and <code>dirname</code> to extract the path of a filename. Eg: dirn..."
 
No edit summary
Line 1: Line 1:
== 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:
<syntaxhighlight lang="bash">
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
</syntaxhighlight>
Function:
<syntaxhighlight lang="bash">
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
}
</syntaxhighlight>
=== die ===
Similar to the <code>die</code> command in PHP which prints out a message before stopping execution.
Function:
<syntaxhighlight lang="bash">
function die {
echo $@
exit
}
</syntaxhighlight>
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.


== Extracting / Parsing Filenames ==
== Extracting / Parsing Filenames ==
Line 26: Line 88:
  ^ (XOR)  | (OR)  & (AND)
  ^ (XOR)  | (OR)  & (AND)


== Control Blocks ==
=== Switch ===
<syntaxhighlight lang="bash">
read -p "What do you want to do?: " Option
case "$Option" in
"K")
install_new_kernel
die "Complete!"
;;
"H")
usage
;;
*)
die "Stopping installation."
;;
esac
</syntaxhighlight>
== 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


[[Category:Linux]]
[[Category:Linux]]
{{Navbox Linux}}
{{Navbox Linux}}

Revision as of 18:19, 31 March 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.


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