Ref: https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html
$1, $2, $3, ... are the positional parameters."$@" is an array-like construct of all positional parameters, {$1, $2, $3 ...}."$*" is the IFS expansion of all positional parameters, $1 $2 $3 ....$# is the number of positional parameters.$- current options set for the shell.$$ pid of the current shell (not subshell).$_ most recent parameter (or the abs path of the command to start the current shell immediately after startup).$IFS is the (input) field separator.$? is the most recent foreground pipeline exit status.$! is the PID of the most recent background command.$0 is the name of the shell or shell script.By default, I'd use [[…]] over […] to simplify the checked code. (Do some Google'ing to find out why)
The square brackets are the test command. Double brackets are an improved variant.
if [[ $(whoami) != "root" ]]; then
printf "The 'root' user is NOT running this script - switch to root and try again!"
fi
myArray=("item1" "item2" "item3")
for item in $(myArray[@]); do
echo $item
done
Redirect the stout of command to cmd.log, and additionally, redirect sterr to the same location as stout
command > cmd.log 2>&1
stdin-n 1 tells read to accept 1 character then process the input - no need to press Return$REPLY contains the value obtained by readread -p "Are you sure? " -n 1 -r
if [[ $REPLY =~ ^[Yy]$ ]]; then
<do something>
fi
Ignoring variable and command expansion
bash -c "cat > /some/file.txt"<<'EOF'
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Sociis lacus leo ultricies lobortis lectus bibendum leo rhoncus.
Taciti aliquet auctor conubia mauris tellus porttitor luctus consequat.
EOF
The trap command is used to capture a system signal, such as SIGINT or SIGTERM
I've used trap to reset the terminal's ANSI after a user has SIGINT'ed the running script
names=(
"john"
"joey-joe-joe"
"jane"
)
# Accessing values
echo ${names[2]} # Outputs "jane"
declare -A names
names=(
[John]=Doe
[Jane]=Doe
[Jim]=Smith
[Angela]=Merkel
)
for i in "${!names[@]}"
do
first_name=$i
last_name=${names[$i]}
echo "$first_name : $last_name"
done
To accept arguments on script execution, use getopt
The sequence :- within a variable expansion (${variable:-word}) is a parameter expansion operator used to provide a default value if the variable is unset or null.
echo ${variable:-word}
To access a variable who's name is provided by another variable
For example
var1=foo
var2="var1"
echo ${!var2}
# Outputs: foo
NOTE: Trying to expand a variable name that is unset will result in an error. For instance, trying to check if the expanded variable is set - if it is in fact unset, you'll get an error about the referring variable being unbound.