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 statements

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.

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

don't forget to do sanity check after converting.

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>

only add executable for file not folder

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

pass parameters in 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

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

reinvoke

if [[ $? -ne 0 ]]; then
     LogMsg "######ERROR: Something went wrong… "
     <shell function name>
fi

猜你喜欢

转载自www.cnblogs.com/chengdol/p/10429185.html