Bash scripts

The latest DL (137) talks about a letter that came in about how to learn more about bash scripts. Thought this would be a great place to maybe get a collection of scripts going.

To start things off a basic back up script:

#!/bin/bash

#generic server backup

DIR=“weeklyserverbackups”

DATE=date +%a-%d-%b-%y-%I-%M-%S-%p-%Z

SERVER=uname -n

echo “Starting back up for $SERVER…”

mdir -p /backup/$DIR/$SERVER

find . -name “*.tar.gz” -mtime +45 | xargs rm

#System Files Backup

echo “Backing up $SERVER /etc…”

tar -cvzPf /backup/$DIR/$SERVER/$SERVER-$DATE-etc.tar.gz /etc

echo “Backing up $SERVER /home…”

tar -cvzPf /backup/$DIR/$SERVER/$SERVER-$DATE-home.tar.gz /home

echo “Backing up $SERVER /var/log…”

tar -cvzPf /backup/$DIR/$SERVER/$SERVER-$DATE-logs.tar.gz /var/log

echo “Backing up $SERVER /var/www…”

tar -cvzPf /backup/$DIR/$SERVER/$SERVER-$DATE-www.tar.gz /var/www

echo “Dumping $SERVER MySQL database files…”

mysqldump -u root -pYOURPASSWORD YOURDB > /backup/YOURDB.sql

echo “Backing up $SERVER MySql files…”

tar -cvzPf /backup/$DIR/$SERVER/$SERVER-$DATE-mysql.tar.gz /var/lib/mysql

echo “Remove backups older then 14 days…”

find /backup/$DIR/$SERVER/* -mtime +4 -exec rm -f {} ;

echo “Finshed removing backups older then 6 days…”

echo “Done.”

OK, one of my over-engineered scripts I use on ALL Debian base distro, (I have another for Arch based distros). This one I call ‘dup’ but you can rename it to whatever suits you.

#!/bin/bash
#
# D Up (Debian Update)
#

_VERSION_="(c) Copyright 2019 by Terry Love (v1.15-2019.08.20)"


_BASENAME_="${0##*/}"           # basename of this script file


# ######################################################
# define colour strings for display messages
#
_RED_='\e[1;31m'
_GREEN_='\e[1;32m'
_YELLOW_='\e[1;33m'
#_BLUE_='\e[1;34m'
#_MAGENTA_='\e[1;35m'
_CYAN_='\e[1;36m'
#_WHITE_='\e[1;37m'
_RESET_='\e[m'



# ######################################################
# version()
#
version() {
echo -e "${_YELLOW_}
    ${_BASENAME_^^}:${_RESET_}version
        ${_CYAN_}${_VERSION_}
${_RESET_}
"
}


# ######################################################
# help()
#
help() {

    echo -e "${_YELLOW_}
    ${_BASENAME_^^}:${_RESET_}help
    ${_YELLOW_}D${_RESET_}(ebian) ${_YELLOW_}UP${_RESET_}(date) is a simple way to start a system update for an Debian
    based distribution, (e.g. Debian, MX, Ubuntu, Mint, SparkyLinux, etc).
    By default it simply invokes :-

        ${_CYAN_}sudo apt update ${_YELLOW_}
        ${_CYAN_}sudo apt dist-upgrade ${_YELLOW_}
        ${_CYAN_}sudo apt autoremove${_RESET_}

    USAGE:

        ${_YELLOW_}${_BASENAME_}${_RESET_}                   default - do update
        ${_YELLOW_}${_BASENAME_} ${_RESET_}[${_CYAN_}<option>${_RESET_}]

    where ${_CYAN_}<option>${_RESET_} can be

        ${_CYAN_}--version${_RESET_} or ${_CYAN_}-v${_RESET_}       to display the version of this script
        ${_CYAN_}--help${_RESET_}    or ${_CYAN_}-h${_RESET_}       to display this help message
"

}


# ######################################################
# OK, let's do this
#
do_update() {

    echo -e "${_CYAN_}\n**** Checking for sudo privilages ****${_RESET_}"
    sudo ls >/dev/null


    echo -e "${_GREEN_}\n**** ${_YELLOW_}${_BASENAME_^^}${_GREEN_} Starting Update\n****${_RESET_}"

    echo -e "${_CYAN_}**** apt update${_RESET_}"
    if sudo apt update ; then
    	echo -e "${_CYAN_}**** apt dist-upgrade${_RESET_}"
    	if sudo apt dist-upgrade -yy ; then
    		echo -e "${_CYAN_}**** apt autoremove${_RESET_}"
    		if sudo apt autoremove -yy ; then
		        echo -e "${_GREEN_}****\n**** ${_YELLOW_}${_BASENAME_^^} ${_GREEN_}SUCCESS${_RESET_}\n"
    		fi
    	fi

    else

        echo -e "${_RED_}****\n**** ${_YELLOW_}${_BASENAME_^^} ${_RED_}FAILED${_RESET_}\n"

    fi

}


# ######################################################

case ${1} in

    "--version" | "-v")
        version
        exit
        ;;


    "--help" | "-h")
        help
        exit
        ;;


    "" | "--update" | "-u")
        do_update
        exit
        ;;


    *)
        echo -e "\n${_RED_}Invalid option : '${1}'${_RESET_}"

        help
        exit 1
        ;;


esac

Silly huh?

1 Like

Here’s another, this one runs dd to burn an .iso to a USB and saves typing and me having to remember the option.

NOTE: This defaults the USB device to /dev/sdc but if you only have 1 HDD/SSD change the default to /dev/sdb or whatever your USB gets mounted on… if you screw up you could whipe out the HDD/SSD on the device you specify - you have been warned

#!/bin/bash
#
#   Dec 19, 2018, 15:37:43
#
set -e

_SCRIPT_="${0##*/}"						# basename of this script file
_USBDEV_="/dev/sdc"	                    # default USB device to use (optional)
_ISOFILE_="${1}"						# filename.iso argument (must have)

# Hi-light colors
#
_RED_='\e[1;31m'
_GREEN_='\e[1;32m'
_YELLOW_='\e[1;33m'
_BLUE_='\e[1;4;34m'
_CYAN_='\e[1;36m'
_WHITE_='\e[1;37m'
_RESET_='\e[m'


# --- show help screen ---
#
show_help() {

_CMD_="${_RED_}${_SCRIPT_}${_RESET_}"
_FNAME_="${_GREEN_}filename.iso${_RESET_}"
_OPTIONAL_="[${_GREEN_}/dev/sdX${_RESET_}]"
_USB_="${_GREEN_}${_USBDEV_}${_RESET_}"
_SUDO_="${_BLUE_}sudo${_RESET_}"
_DD1_="${_YELLOW_}dd bs=4M status=progress if="
_DD2_="${_YELLOW_}of="
_DD3_="${_YELLOW_}&& sync${_RESET_}"


echo -e "${_CYAN_}
    USAGE:
            ${_CMD_} ${_FNAME_} ${_OPTIONAL_}

    ${_CMD_} uses the 'dd' command to write an .iso image to a USB
    memory stick. It expects the filename of the .iso image as an
    argument.

    This version defaults to ${_USB_} for the USB device. Change the
    value of the _USBDEV_ variable to match the configuration for your
    computer. Alternatively you can specify the USB device as an optional
    2nd argument.

    ${_CMD_} require root priviledge and uses the 'sudo' option, e.g.

    ${_SUDO_} ${_DD1_}${_FNAME_} ${_DD2_}${_USB_} ${_DD3_}
"


exit 0

}


# --- execute the dd command to write image to USB ---
#
execute_dd() {

cat << _EOF_

*** Starting dd => USB ***

    sudo dd bs=4M status=progress if=${_ISOFILE_} of=${_USBDEV_} && sync

_EOF_

sudo dd bs=4M status=progress if="${_ISOFILE_}" of="${_USBDEV_}" && sync

cat << _EOF_

*** Completed ***

_EOF_

exit 0

}


# --- the filename provided doesn't exist or is invalid ---
#
file_err() {

cat << _EOF_

    ERROR:

        The file '${_ISOFILE_}' does not exist, is a directory, or is
        otherwise invalid

_EOF_

exit 1

}


# --- an undocumented option to change the value of _USBDEV_
#
hidden_option() {

_YES_NO_="N"

echo

read -erp "Use device ${1} for the USB device? [N/y]:" -n 1  _YES_NO_

if [ "${_YES_NO_}" == "Y" ] || [ "${_YES_NO_}" == "y" ]; then
#    for a [Y/y]es response update _USBDEV_
#

	_USBDEV_="${1}"

    echo -e "${_WHITE_}
Proceeding...
${_RESET_}"

else
#    for a [N/n]o (actually anything but a yes) exit 1
#
	echo -e "${_WHITE_}
Quitting
${_RESET_}"

    exit 1

fi

}

# ###########################################################################
#
# --- Start here ---
#

if [ "${2}" != "" ]; then
#    option to change the default value of _USBDEV_
#

	hidden_option "${2}"

fi


if [ "${_ISOFILE_}" == "--help" ] || [ "${_ISOFILE_}" == "" ]; then
#     check if help is required
#

	show_help

elif [ -f "${_ISOFILE_}" ]; then
#    the .iso file exists and is valid
#

	execute_dd "${_ISOFILE_}"

else
#    file doesn't exist or is invalid
#

	file_err "${_ISOFILE_}"

fi

exit 0

This is an old script and a bit of a mess, adding colours was an afterthought and a bit kludgy

1 Like

What the heck, here’s ‘aup’ - the Arch UPdate variant

#!/bin/bash
#
# A Up (Arch/Arco Update) - also Manjaro
#

_VERSION_="(c) Copyright 2019 by Terry Love (v1.5-2019.08.14)"


_BASENAME_="${0##*/}"           # basename of this script file


# ######################################################
# define colour strings for display messages
#
_RED_="\e[1;31m"
_GREEN_="\e[1;32m"
_YELLOW_="\e[1;33m"
#_BLUE_="\e[1;34m"
#_MAGENTA_="\e[1;35m"
_CYAN_="\e[1;36m"
#_WHITE_="\e[1;37m"
_RESET_="\e[m"



# ######################################################
# version()
#
version() {
echo -e "${_YELLOW_}
    ${_BASENAME_^^}:${_RESET_}version
        ${_CYAN_}${_VERSION_}
${_RESET_}
"
}


# ######################################################
# help()
#
help() {

    echo -e "${_YELLOW_}
    ${_BASENAME_^^}:${_RESET_}help
    ${_YELLOW_}A${_RESET_}(rch) ${_YELLOW_}UP${_RESET_}(date) is a simple way to start a system update for an Arch 
    based distribution, (Arch, Arco, Manjaro or others). It simply invokes
        
        ${_CYAN_}sudo pacman -Syyu${_RESET_}
        
    by default. 
    
    USAGE:

        ${_YELLOW_}${_BASENAME_}${_RESET_}                   default - do update
        ${_YELLOW_}${_BASENAME_} ${_RESET_}[${_CYAN_}<option>${_RESET_}]

    where ${_CYAN_}<option>${_RESET_} can be
        
        ${_CYAN_}--version${_RESET_} or ${_CYAN_}-v${_RESET_}       to display the version of this script  
        ${_CYAN_}--help${_RESET_}    or ${_CYAN_}-h${_RESET_}       to display this help message
"

}


# ######################################################
# OK, let's do this
#
check_sudo() {

echo -e "${_CYAN_}
**** Checking for sudo privilages ****${_RESET_}"

    sudo ls >/dev/null

}

start_update() {

echo -e "${_GREEN_}
**** ${_YELLOW_}${_BASENAME_^^}${_GREEN_} Starting Update
****${_RESET_}"

}

it_failed() {

echo -e "${_RED_}****
**** ${_YELLOW_}${_BASENAME_^^} ${_RED_}FAILED${_RESET_}"

}

it_worked() {

echo -e "${_GREEN_}****
**** ${_YELLOW_}${_BASENAME_^^} ${_GREEN_}SUCCESS${_RESET_}"

}

# ------------------------------------------------------

update() {

    check_sudo


    start_update

    if ! sudo pacman -Syyu; then    
        it_failed
    else                            
        it_worked
    fi

}


# ######################################################

case ${1} in

    "--version" | "-v")
        version
        exit
        ;;
        
        
    "--help" | "-h")
        help
        exit
        ;;
        
        
    "" | "--update" | "-u")
        update
        exit
        ;;
        
        
    *)
        echo -e "${_RED_}
Invalid option : '${1}'${_RESET_}"

        help
        exit 1
        ;;

esac

It works on ArcoLinux, Manjaro and EndeavourOS

1 Like

Toggle screen blanking on and off in gnome based setting idle delay to 0.
Set a keyboard shortcut so I could toggle it.

#!/usr/bin/bash
#Toggle idle-delay to enable/disable screen blanking in gnome
IDLEDELAY=$(gsettings get org.gnome.desktop.session idle-delay | awk {'print $2'})
#How long in seconds to set the idle delay when setting screen blanking to on 
TIMER=300
#ICONS for the notifcation
ICON_ON="/usr/share/icons/Papirus-Dark/symbolic/status/my-caffeine-off-symbolic.svg"
ICON_OFF="/usr/share/icons/Papirus-Dark/symbolic/status/my-caffeine-on-symbolic.svg"

if [[ "${IDLEDELAY}" != "0" ]]
        then
                gsettings set org.gnome.desktop.session idle-delay 0    
                notify-send "Screen Blanking DISABLED" -i ${ICON_OFF}
        else
                gsettings set org.gnome.desktop.session idle-delay ${TIMER}     
                notify-send "Screen Blanking ENABLED, Idle-Delay set For ${TIMER} Seconds" -i ${ICON_ON}
fi