Bash shell

Shell脚本编程30分钟入门

1. $开头shell变量的含义:

  • $1, $2, $3, ... are the positional parameters.
  • "$@" is an array-like construct of all positional parameters, {$1, $2, $3 ...}.
  • "$*" is the IFS expansion of all positional parameters, $1 $2 $3 ....
  • $# is the number of positional parameters.
  • $- current options set for the shell.
  • $$ pid of the current shell (not subshell).
  • $_ most recent parameter (or the abs path of the command to start the current shell immediately after startup).
  • $IFS is the (input) field separator.
  • $? is the most recent foreground pipeline exit status.
  • $! is the PID of the most recent background command.
  • $0 is the name of the shell or shell script.

What are the special dollar sign shell variables?

2. 重定向:

  • 标准输入(stdin):代码为0,使用<<<
  • 标准输出(stdout):代码为1,使用>>>
  • 标准错误输出(stderr):代码为2,使用2>2>>
  • /dev/null:垃圾桶
Paste_Image.png

3. shift:

脚本位置参数左移

4. pushd和popd:

5. awk:

6. source:

使用source命令可以加载其他脚本文件中定义的函数:
https://bash.cyberciti.biz/guide/Source_command

# helper method for providing error messages for a command
run_or_fail() {
  local explanation=$1
  shift 1
  "$@"
  if [ $? != 0 ]; then
    echo $explanation 1>&2
    exit 1
  fi
}
#!/bin/bash

source run_or_fail.sh

# delete previous id
rm -f .commit_id

# go to repo and update it to given commit
run_or_fail "Repository folder not found!" pushd $1 1> /dev/null
run_or_fail "Could not reset git" git reset --hard HEAD

# get the most recent commit
COMMIT=$(run_or_fail "Could not call 'git log' on repository" git log -n1)
if [ $? != 0 ]; then
  echo "Could not call 'git log' on repository"
  exit 1
fi
# get its id
COMMIT_ID=`echo $COMMIT | awk '{ print $2 }'`

# update the repo
run_or_fail "Could not pull from repository" git pull

# get the most recent commit
COMMIT=$(run_or_fail "Could not call 'git log' on repository" git log -n1)
if [ $? != 0 ]; then
  echo "Could not call 'git log' on repository"
  exit 1
fi
# get its id
NEW_COMMIT_ID=`echo $COMMIT | awk '{ print $2 }'`

# if the id changed, then write it to a file
if [ $NEW_COMMIT_ID != $COMMIT_ID ]; then
  popd 1> /dev/null
  echo $NEW_COMMIT_ID > .commit_id
fi
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • DYA3 前两天天气阴晴不定,终于在京都的最后一天迎来了阳关灿烂好天气。今天上午去京都南边的伏见稻荷大社,下午去清...
    菜泡饭阅读 222评论 0 1
  • 先勾画出轮廓,然后用浅蓝色打底 按照花线用浅蓝色打底后,用浅紫色继续打底 最后用深蓝色掩盖部分打底色,将轮廓突出,...
    蛋糕小姐阅读 734评论 0 3
  • 时间过得太快了,眼见着第二阶段的课程也结束了。对我而言,通过第二阶段的学习,得到了很多知识,也得到了很多经验。 第...
    有趣的谷粒阅读 424评论 2 2