【问题标题】:Explain some tips of bash解释bash的一些tips
【发布时间】:2012-04-19 14:11:55
【问题描述】:

我得到一段 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 行。这应该是一个错误,除非其中一个命令产生一个有效的命令名称,它们不应该,并且应该引用它而不是依赖于分词。他们可能意味着它是一个子shell,前面没有$ 符号来隔离noclobber。另外,不要使用function name() { 语法。如果是 Bash,请使用 name()。如果您正在做一些不寻常的 ksh/bash 多语言库,请使用 function name {
  • 要正确保护带有空格的参数,请将$0 $@ &amp; 更改为"$0" "$@" &amp; -- gnu.org/software/bash/manual/bashref.html#Special-Parameters

标签: bash pid


【解决方案1】:

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

$0 $@ &amp;:

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

【讨论】:

    【解决方案2】:
        command1 && command2
    

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

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

    $@都是参数。

    并且关闭&amp; 将进程发送到后台。

    所有内容都记录在bash manual 中,例如参见部分3.4.2 Special Parameters

    【讨论】:

    • command2 当且仅当 command1 返回退出状态 zero -> 应该是非零 (因为如果command1 的计算结果为零,那么计算command2 是没有意义的 - 表达式保证为假)。
    • @AlexanderPavlov - 该行是 bash 手册中的复制粘贴,但是是的,您当然是正确的。
    • 不同意,bash 手册是正确的。试试这个,例如false &amp;&amp; echo got here VS。 true &amp;&amp; echo got here2。还有,false; echo $?; true ; echo $?。祝大家好运。
    • @AoeAoe 是正确的,bash 手册也是如此。在 bash 中,exit 0 表示成功,在这种情况下计算为 true
    【解决方案3】:
    1. &amp;&amp; 是一个逻辑 AND

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

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

      • $0 是调用脚本的命令

      • $@ 是传递给脚本的所有参数的列表

      • &amp;表示前面的命令应该在后台执行

    【讨论】:

      【解决方案4】:

      这是boolean short-circuiting - 如果&amp;&amp;(和)运算符之前的位计算为false,则无需执行第二部分({} 之间的块。同样的技巧与|| 运算符一起使用,只有在第一个块返回false 时才会执行第二个块。

      【讨论】:

        猜你喜欢
        • 2017-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多