Tips Tricks

Error-Proof Your Variables

export somedir="/home/user/somedir"
rm -rf /$somedir
# IF $somedir is unset or null then it will wipe out root "/"
#
# The failsafe
rm -rf /${somedir:?}

Skip the Long if-else Statements

# INSTEAD of

#!/bin/bash
rsync -azP somefile server1:/tmp
if [ ! $? -eq 0 ]
then
  echo "error with rsync"
  exit 1
fi
echo "continuing next step"

# USE THIS

[ ! $? -eq 0 ] && { echo "error with rsync"; exit 1; } 

The {} braces are basically your then statements separated by ;.

Don’t Rely on Passing Arguments

# Instead of assuming the order of the values was provided as desired like `args` in python
# Rely on `"${@}"1 like kwargs in python

#!/bin/bash
## reads in name and age, has boolean flag "--reset" which changes age to be 1
source functions.sh
get_params "${@}"

# Each of thuese results in the below

./main.sh --name joe --reset --age 25
./main.sh --age 25 --name joe --reset

#> NAME="joe"
#> AGE="25"
#> RESET="true"

Easily Check Your Positional Arguments

name=${1:?"Error: parameter missing Name"}
age=${2:?"Error: parameter missing Age"}

./main joe
#> Error: parameter missing Age

Create a Default Value for a Variable

echo "enter your name"
read name
name=${name:-Unknown}

If a user enters blank, your $name will be set to Unknown. The dash after the colon provides a default fallback value.


Children
  1. Color Output
  2. Create Default Variable Values
  3. Create Loading Animations
  4. Create a Directory and Change into It at the Same Time
  5. Delete All Files in a Folder That Don't Match a Certain File Extension
  6. Displaying Native Gui Notifications from Bash
  7. Dont Rely on Positional Args
  8. Error Proof Your Variables
  9. Globbing Vs Ls
  10. Ignore First N Lines
  11. Multiprocessing in Bash Scripts
  12. Output as File Arg
  13. Pipe Stdout and Stderr to Separate Commands
  14. Quickly Truncate a File
  15. Re Run Cmds
  16. Re Use Cmd Args
  17. Redirect Stout and Stderr Each to Separate Files and Print Both to the Screen
  18. Shorten If Statements
  19. Stdin as Arg
  20. Track Content of File