shell example02

输入值

//相加
add(){
  echo "add two agrs..."
  echo "enter first one: "
  read arg1
  echo "enter second one: "
  read arg2
  return $(($arg1+$arg2))
}

add; echo "the results is: $? !"

//判断输入是否是exit code

returns () {
  return $*
}

read -p 'Exit code:' num
if (returns $num); then          //简化 returns $num && echo true $? || echo false $?
  echo true $?
else
  echo false $?
fi

//显示输入的密码
get_password() {
  if [[ -t 0 ]]; then                                         //如果是在terminal内的话
    read -r -p 'Password: ' -s $1 && echo  // -r不过滤反斜杠;   -s 不显示输入;单用echo实现换行
  else
    return 1
  fi
}

get_password PASSWORD && echo $PASSWORD


  • 录制终端会话的常用方法

文件编辑

//修改文件名大写为小写
for file in [A-Z]*; do
  echo "processing $file"
  mv $file `echo $file | tr [A-Z] [a-z]`
done

//把.htm扩展名修改为.html

for i in *.htm ; do
  echo "processing $i"
  mv $i `basename $i .htm`.html
done

//为参数文件生成.bak文件
while [ $# -gt 0 ]; do
  [[ -e $1 ]] && cp $1 $1.bak && echo "create $1.bak"
  shift
done

查找

//查找匹配文件
find .. -path "*/test/*" ! -name "test.pdf" \( -name "*.txt" -o -name "*.pdf" )\   //最后加上-delete可以删除匹配的文件

文件总数量

count =$(ls *.sh | wc -l)
echo "$count"
posted @ 2016-01-14 15:01  JinksPeng  阅读(158)  评论(0编辑  收藏  举报