Bash programming

Category: /knowledge /linux
Tags: linux

Resource

Common usage

Parameters ————-

  • script name: $0
  • Nst parameter: $1, $2 etc
  • parameter count: $#

Parse short/long parameters

Note: the following section works in bash. But it doesn’t exit for wrong format under ksh.

if ! options=$(getopt -o s:l:udh -l show:,level:,up,down,help -- "$@")
then
  exit 1
fi

set -- $options

This is the common section without error checking above.

while [$# -gt 0]; do
  case $1 in 
    -s|--show)
      shift
      prod_no=$1
      ;;
    -l|--level)
      shift
      depth_level=$1
      ;;
    -u|--up)
      direction="UP"
      ;;
    -d|--down)
      direction="DOWN"
      ;;
    -h|--help)
      echo $usuage
      exit 0
      ;;
    esac
    shift
  done

get current base directory

BASEDIR=$(cd $(dirname $0); pwd)
. $BASEDIR/ksh_functions.sh

or 

if [ -x "$0" ]; then 
  SCRIPTDIR=$(cd -P -- "$(dirname -- "$(command -v -- "$0")")" && pwd -P)
else
  SCRIPT=$0
  echo "${SCRIPT}" | grep "^/" > /dev/null 2>&1
  if [ $? -ne 0 ]; then
    SCRIPT=$(pwd)/${SCRIPT}
  fi
  SCRIPTDIR=$(dirname "${SCRIPT}")
fi

get current computer name

case `uname -n` in
  sq*)
    export MODE=TEST
  ;;
  s[drt]*)
    export MODE=PROD
  ;;
esac

如何从命令行传参数

举一个例子, 我想搜索一个文件时学用这个命令:

find -iname "*something*"

我想用alias来省击键次数, set alias ifind='find -iname "*$1*"', 但这个不好使. 解决的办法是在.bashrc里(当然也可以在别的文件里)定义一个function.

function  ifind() {
  find -iname "*$@*"
}

这样我只用在命令行里敲 ifind something 就成了.

Date

How to specify a date other than today

date +"%m%d%Y" -d 20130903

Basic control

if

if [condition]
  something
then
  somecode
fi

while

while [some_condition]
  do
      commands
  done

for-loop

for i in `seq 1 10`;
do
        echo $i
done    

Condition checking

  • [ -d “$HOME/.z” ] && echo “.z is a directory”
  • [ -h “$HOME/.z” ] && echo “.z is a symlink”
  • [ -z “$HOME/.z” ] && echo “.z does not exist”
  • [ -f “$HOME/.z” ] && echo “.z is a file”

讨论

提示

  • 如果看不到讨论部分, 请暂时关掉adblock in Firefox/Chrome
  • 本网站使用Javascript实现评论功能, 此处外链对提高您的网站PR没有帮助. (潜台词: 请不要灌水, 谢谢)