Bash Commands And Scripting

Mar 25, 2018 10:52 · 300 words · 2 minute read Bash Command Line

Good Resource: Bash Scripting Cheatsheet

find /home/cody/backup -ctime +6 -exec rm -rf {} +  # Delete 6+ day files
find . -type d -empty -delete  # Delete empty dirs
nohup ${COMMAND} &  # Daemonize process
disown
rsync -rtvz --exclude=\'.git\' --delete-after path/to/folder1/ path/to/folder2/ user@192.168.0.1:/destination/folder

# Variables
MYVAR="a_string""another string"
MYVAR=$(date +%F)
echo "$MYVAR"
echo "${MYVAR}"

# Conditionals
[ -d "$var" ] # if directory
[ -e "$var" ] # if file exists
[ -z "$var" ] # if empty
[ -n "$var" ] # if not empty
[ "$x" == "hi" ] # String compare

# Loop through array
sites=( 'google.com' 'test.com' )
for site in ${sites[@]}; do
  echo $site
done

# Loop through multiline variable
echo "$list" | while read -r line; do
    echo " $line"
done

# Loop 
for d in */ ; do
  echo $d
done

# Get User input
echo "Enter info: "
read info
echo "$info"

# Present user with options then act on those options
PS3='Please enter your choice: '
options=("Option 1" "Option 2")
select opt in "${options[@]}"
do
  case $opt in
    "Option 1")
      # Do stuff
      ;;
    "Option 2")
      # Do stuff
      ;;
    *) echo invalid option;;
  esac
done

# Check number of arguments to script
if [ "$#" -ne 2 ]; then
  exit 65
fi

# Colored output
G='\e[0;32m'
NC='\e[0m'
G=$(tput setaf 2) # Green
NC=$(tput sgr0) # No Color
echo -e "${G}Green Font${NC}"

# String/Array matrix and looping
declare -a OPTS
declare -a CONNS
CONNS=()
CONNS[0]='pgcli -h localhost -U user -d db1'
CONNS[1]='pgcli -h localhost -U user -d db2'
OPTS=($(printf '%s\n' "${CONNS[@]}" | awk '{ print $7 }'))
select OPT in "${OPTS[@]}"
do
    CMD=$(printf '%s\n' "${CONNS[@]}" | grep "$OPT")
    eval "$CMD"
    break
done

# Capture multi line output as array present as options
OPTIONS=($(ls -1))
select OPTION in "${OPTIONS[@]}"; do
 echo "$OPTION"
done