Bash
Bash
Reading materials
- https://blog.yossarian.net/2020/01/23/Anybody-can-write-good-bash-with-a-little-effort
- https://will-keleher.com/posts/5-Useful-Bash-Patterns.html
- https://timvisee.com/blog/elegant-bash-conditionals
- https://srobb.net/shellscripting.html
- https://srobb.net/bashtips.html
Select statement
select opt in y n; do
echo $opt
done
This creates a loop where the user can select the option. Use case to break out of the loop.
select opt in y n; do
echo $opt selected
case $opt in
y)
break
;;
n)
break
;;
*)
echo wrong option
;;
esac
done
Bash variables
$USER
$HOSTNAME
$PS1
To Find or List all environment variables
env
This is useful when we want to manage the shell variables properly
Paths
$PATH
$PWD
$REALPATH
Bash Prompt customization
https://stackoverflow.com/questions/5947742/how-to-change-the-output-color-of-echo-in-linux https://www.shellhacks.com/bash-colors/
Startup and initializations
bash
bash --norc
bash --login
bash --noprofile
# etc...
- Bash when started as interactive shell, i.e
bash, will source ~/.bashrc only - Bash when started as login shell, i.e
bash --login|-lwill source the following files in that specific order if it exists. (Referman bashfor more)- /etc/profile
- ~/.bash_profile
- ~/.bash_login
- ~/.profile
- When bash login shell is exits, it sources the following file if it exists,
- ~/.bash_logout
Shopts (Shell options) shopt opt
To print all the enabled options, print the variable $BASHOPTS.
echo $BASHOPTS
Extended globbing or Negative globbing
shopt extglob
ls
ls !(*.mkv)
Conditional statements
-eq Equality operator for numbers
== Equality operator for strings
If statements
# -eq, -ne, -lt, -le, -gt, or -ge
if [[ $var -eq $var2 ]]; then
echo do something
else
echo do something else
fi
# == for equality check; != for non equality check
if [[ $var == "string" ]]; then
echo do something
else
echo do something else
fi
# Note: if you are using [ .. ]; then use = sign instead of ==
Case statements
var="hello"
case $var in
hello)
echo var is hello
;;
world)
echo var is world
;;
*)
echo wrong case
;;
esac
Loops
# Syntax
loop statement; do
done
or
loop statement
do
done
For Loop
number=20
for ((i=0; $i<$number; i=$i+1)); do
echo $i
done
VRX=10
for (( i=1; i<=$VRX; i++)); do echo $i; done
# for file in `ls`; do; something with $file; done;
While Loop
declare cnt=0;
while [ true ]; do
cnt=$((cnt+1));
echo $cnt;
[ -f done.txt ] && echo done || sleep 2;
sleep 5;
done
For loop - lists
names=(Apple Bat Cat Dog Elephant Zebra)
for name in "${names[@]}"; do
echo $name
done
Variables
https://bash.cyberciti.biz/guide/Create_an_integer_variable
Sequence
To generate a sequence of variable names
touch test{0..9}.txt
hg remove adc_capture_data_spray_rx{0..9}.json
Strip some text from a variable
https://tldp.org/LDP/abs/html/string-manipulation.html https://tldp.org/LDP/abs/html/string-manipulation.html
some_string=/home/raveen/tools/scripts/run_cmds/poll_and_plot
echo ${some_string%plot}
echo ${some_string#/home}
Remove last few characters from a string in bash
https://reactgo.com/bash-remove-last-n-characters/
country="portugal"
modified=${country::-3}
echo $modified
modified=${country::-4}
echo $modified # "port"
modified=${country%????}
echo $modified # "port"
Operators
>
>>
Lists
FILENAMES=("file1.txt" "file2.txt" "file3.txt")
echo ${FILENAMES[0]}
echo ${FILENAMES[1]}
Subshell
You can make bash invoke subshell using parenthesis
echo hello && ( echo world ) # echo world runs in a subshell
run_main () {
echo run in main shell
}
run_sub () (
echo run in subshell
)
Reading user input from command line
https://alvinalexander.com/linux-unix/shell-script-how-prompt-read-user-input-bash/
read -p "Enter input: " input
echo $input
Remove set functions and variables
unset fun
CREATE a new file or truncate a file
> file.txt
touch file.txt
Disposing of Unwanted Output
ls -l /bin/usr 2> /dev/null
File descriptors and redirection, reading files
0 - standard input, 1 - standard output, 2 - standard error
ls -l /bin/usr > ls-output.txt 2>&1
ls -l /bin/usr &> ls-output.txt
ls -l /bin/usr &>> ls-output.txt
Reading file as input stream, line by line
for line in $(< filename.txt); do
echo $line
done
or
while read -re line; do
echo $line
done < "filename.txt"
Bash Arithmetic operations
echo $((2+3))
You can also use c code in bash
count=1
((count++))
echo $count
Debugging bash scripts / Stepping thorugh the script line by line
https://stackoverflow.com/questions/9080431/how-execute-bash-script-line-by-line
#!/usr/bin/env bash
set -x
trap read debug
< YOUR CODE HERE >
Print commands executed similar to `-x`. Print standard inputs with `-v` option.
set -v
Ignore aliases and use original command
command bc
To auto cd into a directoty
shopt -s autocd
Bash color codes
<https://misc.flogisoft.com/bash/tip_colors_and_formatting>
Play beep sound
echo -e '\a'
Gotchas
Bash doesnot expand ~ inside quotes
~/file is not same as "~/file"
General
Better way to cd into a directory?
Beware that this could cause bugs.
Write a function for cd
cd () {
builtin cd $1;
clear;
pwd;
ls --color=auto -1Ah --color=auto
}
If you are anything like me and want to instantly ls after cd, this will save you some keystrokes. clear and pwd are optional.
listing files/directories along with absolute paths
realpath *
or
readlink -f *
Check for file / directory exists
https://linuxize.com/post/bash-check-if-file-exists/
[ -f file_path ] && echo file exists || echo file does not exist
[ -d directory_path ] && echo directory exists || echo directory does not exist
Current bash shell process id
echo $$