解释bash的一些提示

时间:2012-04-19 14:11:56

标签: bash pid

我得到了一段用于PID文件控制的代码。

程序员的风格,我不明白..

我不知道 - >

使用&&在

[[ $mypid -ne $procpid ]] **&&**

正确地重新启动自己(在MacosX上不起作用)

$0 $@ &

代码完成......

function createpidfile() {
  mypid=$1
  pidfile=$2
  #Close stderr, don't overwrite existing file, shove my pid in the lock file.
  $(exec 2>&-; set -o noclobber; echo "$mypid" > "$pidfile") 
  [[ ! -f "$pidfile" ]] && exit #Lock file creation failed
  procpid=$(<"$pidfile")
  [[ $mypid -ne $procpid ]] && {
    #I'm not the pid in the lock file
    # Is the process pid in the lockfile still running?
    isrunning "$pidfile" || {
      # No.  Kill the pidfile and relaunch ourselves properly.
      rm "$pidfile"
      $0 $@ &
    }
    exit
  }
}

我迷失了

4 个答案:

答案 0 :(得分:1)

[[ ! -f "$pidfile" ]] && exit表示“如果没有名为$ pidfile的文件,则退出”(使用short-circuit evaluation) - 如果文件存在,则不会评估exit

$0 $@ &

  • $0 - 命令行中的第一个参数(表示可执行文件本身);
  • $@ - 所有剩余的参数传递到命令行;
  • & - 在启动后将流程发送到后台。

答案 1 :(得分:1)

    command1 && command2
当且仅当command1返回退出状态为零时才执行

命令。

$0是实际二进制文件的名称。

$@都是参数。

,结束&将流程发送到后台。

所有内容都记录在bash manual中。第3.4.2 Special Parameters部分

答案 2 :(得分:1)

  1. &&是合乎逻辑的 AND

    如果条件[[ $mypid -ne $procpid ]]为真,则块{...}中的代码将被执行。

  2. $0 $@ &在后​​台重启脚本(使用相同的参数)。

    • $0是调用脚本的命令

    • $@是传递给脚本

    • 的所有参数的列表
    • &表示上一个命令应该在后台执行

答案 3 :(得分:1)

它是boolean short-circuiting - 如果&&(和)运算符之前的位评估为false,那么就不需要执行第二部分({之间的块和}||运算符使用相同的技巧,如果第一个块返回false,则只执行第二个块。