Bash Handbook (🚧Continuous Update)

1. Check if a file path represented by environment variable exists

[[ "$(cat ${ENV_VARIABLE})" ]] || printf "env is not exported."

2. Get the file name from the full path

echo "$basename -a /home/foo/abc.txt"

# Output
abc.txt

3. Extract the specific cell value from a table output

For example, the output of the command nomad node status -address=https://127.0.0.1:4646

ID        DC   Name                              Class   Drain  Eligibility  Status
d88b0888  dc1  oscarzhou-B550-AORUS-ELITE-AX-V2  <none>  false  eligible     ready

If we want to get value of the datacenter dc1 where is [2,2] in the array. The solution is

nomad node status -address=https://127.0.0.1:4646 | awk 'NR==2{print $2}'

# Output 
dc1

For awk, the index starts from 1 not 0. NR==2 specifies the line number, {print $2} specifies the column number.

4. Determine the boolean variable

if [ "$var" = true ]; then 
  ...
fi

5. Add menu/option

function menu() {
    PS3='Please select the option: '
    OPTIONS=(
        'foo'
        'bar'
        'Quit'
    )

    select opt in "${OPTIONS[@]}"
    do
        case $opt in 
            'foo')
                function_foo
                ;;
            'bar')
                function_bar
                ;;
            'Quit')
                break
                ;;
        esac
    done
}

# check if the function exists (bash specific)
if [ "$#" -eq 0 ]; then
  menu
else 
  "$@"
fi

6. Print colorful words

ERROR_COLOR='\033[0;31m';
HIGHLIGHT_COLOR='\033[0;32m';
NO_COLOR='\033[0m';

printf "${HIGHLIGHT_COLOR}Success (green)${NO_COLOR}\n"
printf "${ERROR_COLOR}Failure (red)${NO_COLOR}\n"

7. Compare string

if [[ "${foo}" == "foo" || "${foo}" == "bar" ]]; then 
  ...
fi

8. If condition

# Multi-condition
if [[ "${foo}" == "foo" || "${foo}" == "FOO" ]]; then 
  ...
elif if [[ "${foo}" == "bar" || "${foo}" == "BAR" ]]; then 
  ...
fi

# Check if a variable is empty
if [ -z "$foo" ]; then 
    printf "${ERROR_COLOR}foo is empty${NO_COLOR}\n"
    exit;
fi 

# 

9. Extract the basic semantic version (semver) from file

grep -o '[0-9]*\.[0-9]*\.[0-9]*' <file>

If this post helped you to solve a problem or provided you with new insights, please upvote it and share your experience in the comments below. Your comments can help others who may be facing similar challenges. Thank you!
Buy Me A Coffee
DigitalOcean Referral Badge
Sign up to get $200, 60-day account credit !