常用shell小脚本

 

  1. Usage函数
    function Usage() {
        cat <<-delimiter
        Usage: command [-x] [-v] [-z] [files]
        A short explanation of the operation goese here
        It might be a few lines long, but shoudn't be excessive
        delimiter
    }

     

  2. 转换字符
    tr a-z A-Z <<delimiter
    Working directory $PWD
        uio
            bnm
    delimiter    

     

  3. 重复字符串
    b=uiop
    v=$(printf "%-10s" $b)
    echo "${v// /$b}"
    
    
    printf "%.s$b" {1..10}

     

  4. 转换秒 => hour minute second
    function swap_seconds() {
        if [ "$1" -lt 60 ];then
            echo "full backup lasts $1 seconds"
        elif [ "$1" -lt 3600 ];then
            echo "full backup lasts $[$1/60] minutes $[$1%60] seconds"
        elif [ "$1" -lt 86400 ];then
            echo "full backup lasts $[$1/3600] hours $(($1%3600/60)) minutes $[$1%60] seconds"
        else
            echo 'full backup took too much time!'
        fi
    }
    
    swap_seconds $1

     

    function convert_seconds() {
            local T=$1
            local D=$((T/60/60/24))
            local H=$((T/60/60%24))
            local M=$((T/60%60))
            local S=$((T%60))
    
            (($D > 0)) && printf ' %d days' $D
            (($H > 0)) && printf ' %d hours' $H
            (($M > 0)) && printf ' %d minutes' $M
            ((($D > 0 || $H > 0 || $M > 0) && $S != 0)) && printf ' and '
            (($S > 0 )) && printf '%d seconds\n' $S
    }
    
    convert_seconds $1

     

  5. # encapsulation 
    function checkCommandExists() {
      local cmd="$1"
      if [ -z "$cmd" ]; then
        echo "Usage: checkCommandExists command"
        return 1
      fi
      which "$cmd" >/dev/null 2>&1
      if [ $? -eq 0 ]; then
        return 0
      fi
      return 5
    }
    
    function installPackages() {
      zypper --quiet refresh --force
      for package in "$@"; do
        if ! rpm --verify --quiet "$package"; then
          if ! zypper --quiet --no-gpg-checks install -y "$package"; then
            echo -e "\e[31;5;7mpackage $package installation failed!!!\e[0m"
            exit 5
          fi
        fi
      done
    }
    
    # check docker existence
    checkCommandExists docker || { echo -e '\033[7mdocker is not installed!\033[0m' && exit 5; }
    
    # prerequisites, to install additional software, just add to this array.
    declare -a packages=(
      readline-devel
      libopenssl-devel
      libxslt-devel
      libxml2-devel
      unixODBC-devel
      netcat-openbsd
      libseccomp2
    )
    
    # install prequisites
    installPackages "${packages[@]}"

     

posted @ 2020-12-02 15:24  ascertain  阅读(97)  评论(0编辑  收藏  举报