Bash¶
#!/bin/bash
set -e
set -o pipefail
# https://stackoverflow.com/a/246128/1061279
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
SCRIPT_NAME=$(basename "${0}")
ROOT_DIR="$(git rev-parse --show-toplevel)"
readonly DIR
readonly SCRIPT_NAME
readonly ROOT_DIR
Generate Password¶
Files¶
Delete all files matching a pattern in sub folders
Clear an already existing file
Search root for the name
Create a new blank file
Get file size in bytes
Get the size in bytes of a compressed file
Validate JSON¶
Remove File Extension¶
Extract filename and extension in Bash¶
~% FILE="example.tar.gz"
~% echo "${FILE%%.*}"
example
~% echo "${FILE%.*}"
example.tar
~% echo "${FILE#*.}"
tar.gz
~% echo "${FILE##*.}"
gz
Full File Path¶
Checks¶
# Check if chart dir exists
if [ -d "${CHART_PATH}" ]; then
echo "Chart path already exists, ${CHART_PATH}"
exit 1
fi
# Check if i2c-tools is installed
if ! command -v git &> /dev/null; then
echo "git is not installed"
exit 1
fi
Check if substring is in string
Check empty variable
Single line checks
# Check is variable is null
function is_null {
[ -z "$1" ]
}
# Check if directory exists
function dir_exists(){
[ -d "${1}" ]
}
# Check if command exists
function command_exists(){
command -v "${1}" &> /dev/null
}
is_null "$left" && echo "is null"
String manipulation¶
Get domain without the .com
http://user:[email protected]:80/some/path/url?data&and#hash -> example
# https://unix.stackexchange.com/a/428990/93726
echo "http://user:[email protected]:80/some/path/url?data&and#hash" | sed -e "s/[^/]*\/\/\([^@]*@\)\?\([^:/]*\).*/\2/" | sed "s/^www\.//" | cut -f 1 -d '.'
Checksums¶
Get checksum of remote file
Scripts¶
Get single options, -v, -h, etc.
# https://www.jamescoyle.net/how-to/1774-bash-getops-example
# https://opensource.com/article/19/12/help-bash-program
# Get the options
while getopts ":hv" o; do
case "${o}" in
h) # display Help
help
exit 0;;
v)
printf "${SCRIPT_NAME} version ${APP_VERSION}\n"
exit 0;;
\?) # incorrect option
usageerror;;
esac
done
# https://unix.stackexchange.com/a/214151/93726
shift "$((OPTIND-1))"
Miscellaneous¶
printf
printf "%s is the value" "${var}"
# Expand the tab, \t or new line \n
var="value\t"
printf "%b is the value" "${var}"
Insert first line of file
Delete a tmp dir on exit
Download and extract file in one line. Works with tar & zip files.
Make variable global from inside function
Compare semver
# https://stackoverflow.com/a/4025065/1061279
function vercomp () {
if [[ $1 == $2 ]]; then
return 0
fi
local IFS=.
local i ver1=($1) ver2=($2)
# fill empty fields in ver1 with zeros
for ((i=${#ver1[@]}; i<${#ver2[@]}; i++)); do
ver1[i]=0
done
for ((i=0; i<${#ver1[@]}; i++)); do
if [[ -z ${ver2[i]} ]]; then
# fill empty fields in ver2 with zeros
ver2[i]=0
fi
if ((10#${ver1[i]} > 10#${ver2[i]})); then
return 1
fi
if ((10#${ver1[i]} < 10#${ver2[i]})); then
return 2
fi
done
return 0
}
function testvercomp () {
vercomp $1 $2
case $? in
0) op='=';;
1) op='>';;
2) op='<';;
esac
if [[ $op != $3 ]]; then
echo "The minimum required version of git is $2"
exit 1
fi
}
testvercomp ${GIT_VER} ${MIN_VER} '>'
Generate Random String¶
#!/bin/bash
# Load the myfunctions.sh
# My local path is /home/vivek/lsst2/myfunctions.sh
. /home/vivek/lsst2/myfunctions.sh
# Define local variables
# var1 is not visitable or used by myfunctions.sh
var1="The Mahabharata is the longest and, arguably, one of the greatest epic poems in any language."
# Invoke the is_root()
is_root && echo "You are logged in as root." || echo "You are not logged in as root."
# Find out if user account vivek exits or not
is_user_exits "vivek" && echo "Account found." || echo "Account not found."
# Display $var1
echo -e "*** Orignal quote: \n${var1}"
# Invoke the to_lower()
# Pass $var1 as arg to to_lower()
# Use command substitution inside echo
echo -e "*** Lowercase version: \n$(to_lower ${var1})"
Run As Different User¶
Return Value from Function¶
function myfunc(){
local myresult='some value'
echo "$myresult"
}
result=$(myfunc) # or result=`myfunc`
echo $result
Sort Semver Using Sort¶
printf "1.0\n2.0\n2.12\n2.10\n1.2\n1.10" | sort -t "." -k1,1n -k2,2n -k3,3n
1.0
1.2
1.10
2.0
2.10
2.12
ID (Debian, Ubuntu)¶
Arch¶
Subs aarch64 with arm64, x86_64 with amd64, and armv7l and armv6l with arm
ARCH=$(uname -m | sed -e 's/x86_64/amd64/' -e 's/\(arm\)\(64\)\?.*/\1\2/' -e 's/aarch64$/arm64/')
echo $ARCH
Subs aarch64 with arm64, x86_64 with amd64, and armv7l and armv6l with armhf
ARCH=$(uname -m | sed -e 's/x86_64/amd64/' -e 's/\(arm\)\(64\)\?.*/\1\2hf/' -e 's/aarch64$/arm64/')
echo $ARCH
[Check if system needs to be restarted][2]¶
We use the systemctl command as follows to restart services one-by-one:
We can use bash for loop as follows:
How to restart systemd with PID # 1 without rebooting Linux box
And verify it again:
Check Array for Value¶
if [[ " ${array[*]} " =~ " ${value} " ]]; then
# whatever you want to do when array contains value
fi
if [[ ! " ${array[*]} " =~ " ${value} " ]]; then
# whatever you want to do when array doesn't contain value
fi
Search for string in files¶
If you want to get number of occurrences use wc -l as pipe
Print Colors & Bold¶
for c in {0..255}; do tput setaf $c; tput setaf $c | \cat -v; echo =$c; done | column
See here for colors.
Bypass Alias¶
A simple directive which disables all aliases and functions for the command immediately following it. Shortcut for the bash built-in 'command' - "command linefoo".
Push your present working directory to a stack that you can pop later¶
```shell titl="Remove directory from stack" popd
## Run script in subshell
```shell
sudo -u "${TARGET_USER}" bash <<"EOF"
cd "$HOME"
mkdir -p "${HOME}/git/nicholaswilde/"
git clone https://github.com/nicholaswilde/dotfiles.git "${HOME}/git/nicholaswilde/dotfiles"
cd "${HOME}/git/nicholaswilde/dotfiles"
# set the correct origin
git remote set-url origin [email protected]:nicholaswilde/dotfiles.git
# installs all the things
make
EOF
Get IPv4¶
Show Environmental Variables¶
Show Shell Functions¶
Show Shell Aliases¶
Replace Tabs with Spaces¶
Git Status¶
git diff --quiet; nochanges=$?
if [ $nochanges -eq 0 ]; then
# there are no changes
else
# there are changes
fi
Alternatively, if you don't need to store the exit status in a variable, you can do:
Since git diff is a porcelain Git command and you want to do things programmatically, you should probably use the plumbing Git command called git diff-index instead (which also has a --quiet flag, but which must be supplied a tree-ish argument):
As pointed out in a comment below, the approach outlined above does not cover untracked files. To cover them as well, you can use the following instead:
Relative Path¶
Using realpath from GNU coreutils 8.23 is the simplest, I think:
For example:
Get Between Patterns¶
Test if option is set¶
If you do set -f, or otherwise disable globbing:, $- will contain f:
So:
Or:
References¶
- set -e, -u, -o pipefail explanation
- pure bash bible
- bash-utility
- Cheat Sheet
- commandlinefu
- Password Special Characters