美文网首页
Bash shell

Bash shell

作者: sylcrq | 来源:发表于2016-09-28 15:09 被阅读28次

    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
    

    相关文章

      网友评论

          本文标题:Bash shell

          本文链接:https://www.haomeiwen.com/subject/vxohyttx.html