Guangning Yu's Blog

Bash Basics

2019-02-17 01:40:29  |  shell
  • assign default value to variable
  1. DEFAULT=5
  2. RESULT=${VAR:-$DEFAULT}
  • trap error exit
  1. function rollback() {
  2. if [[ $? -ne 0 ]]; then
  3. echo "rollback"
  4. fi
  5. }
  6. set -ueo pipefail
  7. trap rollback EXIT
  • if file exists
  1. #!/bin/bash
  2. FILE="/etc/passwd"
  3. if [[ -f $FILE ]];then
  4. echo "$FILE exists"
  5. else
  6. echo "$FILE doesn't exist"
  7. fi
  • if directory exists
  1. #!/bin/bash
  2. DIR="/var/log"
  3. if [[ -d $DIR ]]; then
  4. echo "$DIR exists"
  5. else
  6. echo "$DIR doesn't exist"
  7. fi
  • eval
  1. function assert_var_exists() {
  2. local condition="[[ ! -n \"\${$1+set}\" ]]"
  3. if eval $condition; then
  4. echo "The variable ${1} does not exist. Exit."
  5. exit 1
  6. fi
  7. }
  8. function export_var() {
  9. assert_var_exists $1
  10. local var_value=$(($1))
  11. eval "export $1=\$var_value"
  12. echo "$1=$var_value"
  13. }
  • Check platform
  1. uname -m
  2. lsb_release