Commonly Used Code Snippets

This blog collects the commonly used code snippets based on my daily work, also do summary from related stackoverflow topics.

If condition

List of bash condition statements

# sth does not exist?
if [[ "${sth}""X" == "X" ]]; then
  LogMsg "###### INFO: ..."
fi
# directory does not exist?
if [[ ! -d "${folder_path}" ]]; then
   LogMsg "###### ERROR: ${folder_path} directory doesn't exist!"
   exit 1
fi

Script input parameters

Usage()
{
  echo
  echo "Usage $0 ..."
  echo "For example: ..."
}

if [ $# -eq 0 ]
then
  echo "No command-line arguments were specified..."
  Usage
  exit 1
fi

while [ $# -gt 0 ]
do
  case "$1" in
    -flag1)
       shift
       <var1>=${1}
       shift;;

    -flag2)
       shift
       <var2>=${1}
       shift;;

    *) Usage
       exit 1;;
  esac
done

Log message

LogMsg()
{
  logMsg="$@"
  echo "["`date +"%Y/%m/%d %r"`"]" ${logMsg}
}
LogMsg "###### INFO: ..."
LogMsg "###### WARNING: ..."
LogMsg "###### ERROR: ..."

Check last command result

echo_success_failure() {
  if [ $? -eq 0 ]; then 
    LogMsg "###### INFO: Success..."
  else 
    LogMsg "###### INFO: Failure..."
  fi
}

Run as root

effective_uid=`id -u` 2>/dev/null
if [ $effective_uid -ne 0 ]; then
 LogMsg "###### ERROR: Please run this script as root or sudo"  
 exit 1
fi

Delimited string to array

Convert delimited string to array, for example:

string="item1 item2 item3"
IFS=' ' read -a array <<< "${string}"

This version has no globbing problem, the split character is set in $IFS (here is space), variables quoted. Don't forget to do sanity check after converting.

${array[0]}  ===> item1
${array[1]}  ===> item2
${array[2]}  ===> item3

Actually if the string use spaces as delimiter, we can loop items directly:

string="item1 item2 item3"
for i in ${string}
do
  echo ${i}
done

Loop array

declare -a array=("element1" "element2" "element3")
for i in "${array[@]}"
do
   echo "${i}"
done

declare or typeset are an explicit way of declaring variable in shell scripts.

In BASH it is safer to quote the variable using "" for the cases when $i may contain white spaces or shell expandable characters.

If you want to use index of array element

# get length of an array
arraylength=${#array[@]}

# use for loop to read all values and indexes
for (( i=0; i<${arraylength}; i++ ));
do
  echo $i " / " ${arraylength} " : " ${array[$i]}
done

Chmod

chmod recursively for directory and it's content

chmod -R 0755 <target directory>

Or only add executable for file

find . -name '<file name>' -type f | xargs chmod +x
-rwxr-xr-x ...

Pass parameters to script

# invoke, must stick to this format
echo "admin
admin" | ./script.sh
# receive code snippet in script.sh
MsgLog "###### Please enter args1  ..."
read args1
LogMsg "###### Please enter password ..."
read -s password
${args1}     ===> admin
${password}  ===> admin

Note: read -s flag: do not echo input coming from a terminal, used for password

Setup ssh password-less

Idempotence:

ssh-keyscan -H ${remote} >> ~/.ssh/known_hosts
sshpass -p "<password>" ssh-copy-id -i ~/.ssh/id_rsa.pub root@${remote}
if [[ $? -ne 0 ]]; then
  LogMsg "######ERROR: Something went wrong with ssh-copy-id. Check for incorrect credentials ... "
  exit 1
fi

Recursive call

example()
{
  <execute sth>
  if [[ $? -ne 0 ]]; then
       LogMsg "######ERROR: Something went wrong… "
       example
  fi
}
posted @ 2019-02-25 09:31  海胆阶段  阅读(200)  评论(0)    收藏  举报