linux:bash_usefull_snippets
Table of Contents
Bash Usefull Snippets
Are we root
This line makes sure the user is running the script as root or at least sudo.
[[ $UID -ne 0 ]] && { echo "This script must be run as root or use sudo"; exit 1; }
Are we in the right directory
This checks whether a user is in the right directory before doing something.
directory="test2"; [[ "${PWD##*/}" != "$directory" ]] && { printf "\nWrong directory! Script must be run from $directory\n"; exit 1; }
Alternative method, while shorter it hardcoded directory names in 2 places.
[[ "${PWD##*/}" != "directoryname" ]] && { printf "\nWrong directory! Script must be run from directoryname\n"; exit 1; }
Check Php version example 1
This checks for the current Php version and stores only the version number in a variable.
phpver=$(php -v | awk '/^PHP/ {split($2,a,"."); print a[1]"."a[2]}')
Check Php version example 2
This checks for the current Php version and stores only the version number in a variable no AWK needed.
phpver=$(php -r 'echo PHP_MAJOR_VERSION.".".PHP_MINOR_VERSION;')
Check for yes or no
A snippet that checks for yes and no.
if [ "$answer" != "${answer#[Yy]}" ]; then echo Yes else echo No fi
Output banner and title
A simple snippet that outputs a banner and title.
# # Color definition # red='\033[0;31m' ; bred='\033[1;31m' ; green='\033[0;92m' ; blue='\033[0;36m' ; bold='\033[1m' ; normal='\033[0m' # # Function banner # banner () { echo -e "${blue}__ __ _____ _ _" echo -e "${blue}\ \/ / | ___(_) | ___ ___" echo -e "${blue} \ / ___ | |_ | | |/ _ \/ __|" echo -e "${blue} / \ ___ | _| | | | __/\__ \\" echo -e "${blue}/_/\_\ |_| |_|_|\___||___/" } # # Function title # title () { printf "\nYour title goes here${normal}\n\n"; } # # Execute banner and title # banner ; title
Check filesize
Will check for a specific filesize and report back with expected size accordingly.
filename="some-file-name" filesize=$(stat --printf="%s\n" $filename) minimum="100000000" expected=$(( minimum / 1000000 )) if [ "$filesize" -le "$minimum" ]; then printf "File $filename is smaller than $expected"mb." aborting...\n\n" rm $filename ; exit else printf "File $filename is greater than $expected"mb." continuing...\n\n" fi
Loop over an array of items
Subject says it all.
# # Declare array # items=( item1 item2 item3 ) # # Loop over array and do stuff # for i in "${items[@]}" ; do echo $i done
Check sql connections
How to access sql from wihtin bash.
srvstatus=$(systemctl is-active mysqld) if [[ "$srvstatus" != "active" ]]; then printf "\nMariaDB is not running on this server...\n\n"; exit ; fi ; printf "\n" mysql -e "SELECT DB,USER,HOST,STATE FROM INFORMATION_SCHEMA.PROCESSLIST ORDER BY DB DESC;" ; printf "\n"
linux/bash_usefull_snippets.txt · Last modified: by Allan