User Tools

Site Tools


linux:bash_usefull_functions

Bash Usefull Functions

Check if service(s) is running example 1

This will check weather a specific service is running or not and exit depending of what you are checking. This version will accumulate the status of all services before printing the output.

servicecheck() {
    local mode="$1"
    shift
    local bad_services=()
 
    case "$mode" in
        dead)
            for service in "$@"; do
                if [[ "$(systemctl is-active "$service")" != "active" ]]; then
                    bad_services+=("$service")
                fi
            done
            if (( ${#bad_services[@]} > 0 )); then
                echo "The following service(s) appears not to be running cannot continue..."
                for svc in "${bad_services[@]}"; do
                    echo "  - $svc"
                done
                exit 1
            fi
            ;;
        alive)
            for service in "$@"; do
                if [[ "$(systemctl is-active "$service")" == "active" ]]; then
                    bad_services+=("$service")
                fi
            done
            if (( ${#bad_services[@]} > 0 )); then
                echo "The following service(s) appears already to be running cannot continue..."
                for svc in "${bad_services[@]}"; do
                    echo "  - $svc"
                done
                exit 1
            fi
            ;;
    esac
}
 
# Example:
# Check if apache2 and mysql are not running
# servicecheck dead apache2 mysql
#
# Check if nginx and mariadb are running
# servicecheck alive nginx mariadb

Check if service(s) is running example 2

This will check weather a specific service is running or not and exit depending of what you are checking. This is a simpler version the example 1 and will stop as soon as the first check fails.

servicecheck() {
    local mode="$1"
    shift
 
    case "$mode" in
        dead)
            for service in "$@"; do
                if [[ "$(systemctl is-active "$service")" != "active" ]]; then
                    printf "\n%s is not running, cannot continue...\n\n" "$service"
                    exit 1
                fi
            done
            ;;
        alive)
            for service in "$@"; do
                if [[ "$(systemctl is-active "$service")" == "active" ]]; then
                    printf "\n%s is running, cannot continue...\n\n" "$service"
                    exit 1
                fi
            done
            ;;
    esac
}
 
# Example:
# Check that services are dead (fail if any are alive)
# servicecheck dead nginx mariadb
#
# Check that services are alive (fail if any are dead)
# servicecheck alive nginx mariadb

Check if service(s) is running example 3

Another service check approach musch simpler as example 2 and 3.

service_no () { printf "\n$service is not running cannot continue...\n\n"; }
service_yes () { printf "\n$service is allready running cannot continue...\n\n"; }
 
service_dead  () { status=$(systemctl is-active $service); if [[ "$status" != "active" ]]; then service_no ; exit; fi; }
service_alive () { status=$(systemctl is-active $service); if [[ "$status" == "active" ]]; then service_yes ; exit; fi; }
 
# Example:
# Check if MariaDB and Nginx is running if not exit
# service="mariadb" ; service_dead ; service="nginx" ; service_dead
# Check if MariaDB is running if it is the exit
# service="mariadb" ; servicealive ; service="nginx" ; servicealive

Output x chars example 1

line() { printf "%0.s$1" $(seq 1 $2); printf '\n'; }
#
# Execute function print 50 hyphens 
#
line '-' 50
#
# Execute function print 10 plus signs
#
line '+' 10

Output x chars example 2

Same as above but hardcoded printing 50 hyphens

line () { printf -- '-%.0s' {1..50}; printf '\n'; }
#
# Execute function print 50 hyphens
#
line

Output x chars example 2

Note: not as good an implementation as example 2 and example 3, but here as in example 1 you can change what character is being output when calling the function.

line (){ for i in {1..50}; do echo -n "$1"; done && printf "\n"; }
#
# Execute function draw 50 hyphens
#
line '-'

Reboot with countdown

A function to call a reboot displaying a countdown as well.

red='\033[0;31m' ; bred='\033[1;31m' ; green='\033[0;92m' ; blue='\033[0;36m' ; bold='\033[1m' ; normal='\033[0m'
#
# Function: reboot_server [seconds]
#
reboot_server () {
    local wait_time="${1:-10}"   # default to 10 if no argument given
 
    echo -ne "${blue}"
    local temp_cnt=${wait_time}
 
    while [[ ${temp_cnt} -gt 0 ]]; do
        printf "\rRebooting in %2d second(s) - hit ctrl+c to cancel ..." "${temp_cnt}"
        sleep 1
        ((temp_cnt--))
    done
    echo -e "${normal}"  # reset color after countdown
    reboot
}
 
# Example:
# reboot_server         # defaults to 10 seconds
# reboot_server 30      # 30 second countdown
# reboot_server 60      # 60 second countdown

Check if we are in the right directory

A function that checks weather the user is in the right directory or not remember to use quotes around the directory name.

must_be_in_dir() {
    local required_dir="$1"
    if [[ "${PWD##*/}" != "$required_dir" ]]; then
        printf "\nWrong directory! This script must be run from '%s'\n" "$required_dir"
        exit 1
    fi
}
 
# Example:
# must_be_in_dir "nginx-install"

Are we root Example 1

Check if the user is root or at least sudo when running the script.

must_be_root() {
    local required="$1"
 
    if [[ "$required" == "yes" ]]; then
        if [[ $UID -ne 0 ]]; then
            echo "This script must be run as root or use sudo"
            exit 1
        fi
    fi
}
 
# Example:
# must_be_root yes

Are we root Example 2

Check if the user is root or at least sudo when running the script. A bit shorter code but the outcome is the same.

must_be_root() {
    if [[ $UID -ne 0 ]]; then
        echo "This script must be run as root or use sudo"
        exit 1
    fi
}
 
# Example: Note that we are not calling it using "must_be_root yes" but only "calling must_be_root"
must_be_root
linux/bash_usefull_functions.txt · Last modified: by Allan