Bash Scripting: Difference between revisions

From Leo's Notes
This page was last edited on 28 September 2015, at 06:07.
Moved long snippets to phorkie. Formatting
Line 1: Line 1:
== Common Functions ==
== Useful Functions / Utilities ==
Here are some common functions I use in my scripts.
Here are some common functions I use in my scripts.


Line 6: Line 6:


Example Usage:
Example Usage:
<syntaxhighlight lang="bash">
{{Highlight|lang=bash|code=
  if prompt "Is this okay?" Y ; then
  if prompt "Is this okay?" Y ; then
     echo "It's Okay!"
     echo "It's Okay!"
Line 13: Line 13:
     echo "It's not okay!"
     echo "It's not okay!"
  fi
  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?
Source:
if [ -z "$REPLY" ]; then
<phorkie>https://phorkie.leo.home.steamr.com/13/embed</phorkie>
REPLY=$default
fi
 
# Check if the reply is valid
case "$REPLY" in
Y*|y*) return 0 ;;
N*|n*) return 1 ;;
esac
done
}
</syntaxhighlight>


=== die ===
=== die ===
Line 59: Line 29:
</syntaxhighlight>
</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.
{{Info|Caveat when using in a subshell|This will not work inside a subshell as it will just quit the subshell rather than the script. To get around this, you may need to kill the parent PID instead.}}


=== Indent ===
=== Indent ===
Indents text piped to the function.
Indents text piped to the function.


Function:
Source:
<syntaxhighlight lang="bash">
<phorkie>https://phorkie.leo.home.steamr.com/14/embed</phorkie>
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
}
</syntaxhighlight>


Usage:
Usage:
<syntaxhighlight lang="bash">
{{Highlight|lang=bash|code=
echo "test" | Indent
echo "test" | Indent
test
test
echo "test" | Indent 2
echo "test" | Indent 2
test
test
</syntaxhighlight>
}}


== Extracting / Parsing Filenames ==
=== 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.
Use the <code>basename</code> to extract filenames from a path and and <code>dirname</code> to extract the path of a filename.


Eg:
Eg:
dirname /etc/hosts
{{Highlight|lang=bash|code=
/etc
$ dirname /etc/hosts
/etc
}}


basename /etc/hosts
{{Highlight|lang=bash|code=
hosts
$ basename /etc/hosts
hosts
}}


To extract only the extension or the filename without the extension, use bash's string matching:
To extract only the extension or the filename without the extension, use bash's string matching:
Filename=$(basename /etc/resolv.conf)
{{Highlight|lang=bash|code=
Ext="${Filename##*.}"
Filename=$(basename /etc/resolv.conf)
Name="${Filename%.*}"
Ext="${Filename##*.}"
Name="${Filename%.*}"
}}


== Arithmetic Operations ==
== Arithmetic Operations ==
Do integer arithmetic operations on variables within double brackets. For example:
Do integer arithmetic operations on variables within double brackets. For example:
Value=1
{{Highlight|lang=bash|code=
ValuePlusOne=$((Value + 1))
Value=1
ValueTimes12=$((Value * 12))
ValuePlusOne=$((Value + 1))
ValueTimes12=$((Value * 12))
}}


The operators that are supported are:
The operators that are supported are:
  + - / * %  
  + - / * %  
Bitwise operators also work:
Bitwise operators also work:
  ^ (XOR)  | (OR)  & (AND)
  ^ (XOR)  | (OR)  & (AND)


== Control Blocks ==
== Control Blocks ==

Revision as of 06:07, 28 September 2015

Useful Functions / Utilities

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

Source: <phorkie>https://phorkie.leo.home.steamr.com/13/embed</phorkie>

die

Similar to the die command in PHP which prints out a message before stopping execution.

Function:

function die {
	echo $@
	exit
}
Caveat when using in a subshell
This will not work inside a subshell as it will just quit the subshell rather than the script. To get around this, you may need to kill the parent PID instead.


Indent

Indents text piped to the function.

Source: <phorkie>https://phorkie.leo.home.steamr.com/14/embed</phorkie>


Usage:

echo "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