Functions in Bash

#!/bin/bash
# Basic function
print_something () {
echo Hello I am a function
}
print_something
print_something

Passing Arguments

#!/bin/bash
# Passing arguments to a function
print_something () {
echo Hello $1
}
print_something Mars
print_something Jupiter

Return Values

#!/bin/bash
# Setting a return status for a function
print_something () {
echo Hello $1
return 5
}
print_something Mars
print_something Jupiter
echo The previous function has a return value of $?

Passing Arguments

#!/bin/bash
# Passing arguments to a function
print_something () {
echo Hello $1
}
print_something Mars
print_something Jupiter

Return Values

#!/bin/bash
# Setting a return status for a function
print_something () {
echo Hello $1
return 5
}
print_something Mars
print_something Jupiter
echo The previous function has a return value of $?

the variable $? contains the return status of the previously run command or function.

References
https://ryanstutorials.net/bash-scripting-tutorial/bash-functions.php

If Statements in Bash

Basic If Statements

#!/bin/bash
# Basic if statement
if [ $1 -gt 100 ]
then
echo Hey that\'s a large number.
pwd
fi
date

If Else

#!/bin/bash
# else example
if [ $# -eq 1 ]
then
nl $1
else
nl /dev/stdin
fi

If Elif Else

#!/bin/bash
# elif statements
if [ $1 -ge 18 ]
then
echo You may go to the party.
elif [ $2 == 'yes' ]
then
echo You may go to the party but be back before midnight.
else
echo You may not go to the party.
fi

Boolean Operations

#!/bin/bash
# and example
if [ -r $1 ] && [ -s $1 ]
then
echo This file is useful.
fi
#!/bin/bash
# or example
if [ $USER == 'bob' ] || [ $USER == 'andy' ]
then
ls -alh
else
ls
fi

Multiple logical operators, ((A || B) && C)

use double brackets

if [[ ($A -eq 0 || $B -ne 0) && $C -eq 0 ]]; then …

References
https://ryanstutorials.net/bash-scripting-tutorial/bash-if-statements.php
https://unix.stackexchange.com/questions/290146/multiple-logical-operators-a-b-c-and-syntax-error-near-unexpected-t

User Input in Bash

Ask the User for Input

#!/bin/bash
# Ask the user for their name
echo Hello, who am I talking to?
read varname
echo It\'s nice to meet you $varname

More variables

#!/bin/bash
# Demonstrate how read actually works
echo What cars do you like?
read car1 car2 car3
echo Your first car was: $car1
echo Your second car was: $car2
echo Your third car was: $car3

More with Read

#!/bin/bash
# Ask the user for login details
read -p 'Username: ' uservar
read -sp 'Password: ' passvar
echo
echo Thankyou $uservar we now have your login details

-p allows you to specify a prompt and -s makes the input silent

References
https://ryanstutorials.net/bash-scripting-tutorial/bash-input.php