Some Basic Bash-Script Code Block
29 Nov, 2022
Some basic bash-script code example. It might be help if writing some temporary work-scripts.
Assignment and Substitution
a=375
hello=$a
Variables
- Built-in Variables
For example$HOME $PWD ...
, for more info, see environ(7) - Positional Parameters
echo para2 para4 1 3 @ - Special Parameters
$? # exit status of a command, function, or the script itself
Branches
if [ condition1 ];then
command_series1
elif [ condition2 ];then
command_series2
else
default_command_series3
fi
Loops
range for
for arg in `seq 10`; do
echo $arg
done
for in C-like syntax
LIMIT=10
for ((a=1; a<=LIMIT; a++)); do
echo "$a "
done
while
LIMIT=10
a=1
while ((a<=LIMIT)); do
echo "$a "
((a += 1))
done
IO
command < input-file > output-file # rewrite
command >> output-file # appending
Function
# define a function
function fun_name(){
command...
}
## or
fun_name(){ # arg1 arg2 arg3
command...
}
# apply a function
fun_name $arg1 $arg2 $arg3
# dereference
fun_name(){ # arg1
eval "$1=hello"
}
fun_name arg1
## the above code block is equivalent to
arg1=hello
Debugging
- take good use of sh(1)
for example:
sh -n script: checks for syntax
sh -v script: echo each command before executing it
sh -x script: echo the result of each command in an abbreviated manner - use echo
- use trap
Parallel
use GNU parallel
Script with Style
- Comment your code
- Avoid using magic number
- Use exit codes in a systematic and meaningful way
- Use standardized parameter flags for script invocation