BASH
Basics
For details: https://devhints.io/bash
Printing
echo "Hello". # Print with new line
echo -n "Hello" # No new line
Variable
var="hello"
echo $var
echo "$var"
echo ${var}
Execute shell command
echo "The current path is $(pwd)"
echo "The current path is `pwd`"
Brace expansion
echo {file1,file2}.sv
{A,B} # same as A B
{A,B}.sv # Same as A.sv B.sv
{1..4} # Same as 1 2 3 4
Airthmetic operation
sum=$(($a+$b-2))
Branching statement
# if-elif statement
if [[ -z "$string" ]]; then
echo "String is empty"
elif [[ -n "$string" ]]; then
echo "String is not empty"
fi
# if-else statement
if [[ -d "DIR" ]]; then
echo "Directory exist"
echo "Demostrating compound statement"
else
echo "Directory doesn't exist"
fi
Note:
-f can be used to check if file exist
!-f can be used to check if file doesn't exist
-d can be used to check if directory exist
!-d can be used to check if directory doesn't exist
Loops
Basic loop through files
for i in /path/file*; do
echo $i
done
Reading a file
cat file.txt | while read line; do
echo $line
done
Reading a file
while read line
do
echo $line
done < file.txt
Alternate format
for ((i = 0 ; i < 100 ; i++)); do
echo $i
done
Superloop
while true; do
···
done
Range with step size (optional)
for i in {5..50..5}; do
echo "Welcome $i"
done
Associative array
# An array with named index i.e. a key-value pair
declare -A sounds
# Keys -> dog, cow, bird, wolf
# Value-> bark, moo, tweet, howl
sounds[dog]="bark"
sounds[cow]="moo"
sounds[bird]="tweet"
sounds[wolf]="howl"
# Access
echo ${sounds[dog]} # bark - Dog's sound
echo ${sounds[@]} # All values
echo ${!sounds[@]} # All keys
echo ${#sounds[@]} # Number of elements
unset sounds[dog] # Delete dog
# iterate over values
for val in "${sounds[@]}"; do
echo $val
done
# iterate over keys
for key in "${!sounds[@]}"; do
echo $key
done
Incremental directory name
# While reruns, we might need to preserve few older logs. It will be convenient if the script can automatically
# number them. The following snipped does that.
n=1
# Increment $N as long as a directory with that name exists
while [[ -d "Dir_${n}" ]] ; do
n=$(($n+1))
done
mkdir "Dir_${n}"
Check if file/directory exist
#Check if file exits
if [ -f "$FILE" ]; then
echo "$FILE exist"
fi
# Check if file does not exist
if [ ! -f "$FILE" ]; then
echo "$FILE does not exist"
fi
# Check if directory exist
if [ -d $DIR ]; then
echo "Directory $DIR exist"
if
Random number
export rndNum=$(($RANDOM % 99))
INPUTRC
"\ep": history-search-backward
"\en": history-search-forward
set show-all-if-ambiguous on
set completion-ignore-case on
Useful constructs
colrm - Remove a column char by char
e.g.:
colrm 10 # Remove everything after 10 characters. If 1 argument then second arg is $
colrm 1 5 # Remove column 1 to 5