Ignore empty results for xargs in Mac OS X

前端 未结 4 2001
迷失自我
迷失自我 2021-02-07 10:36

The code for my website uses this piece of code for automatic deployment on the server (Ubuntu).

cmd = \'cd \' + checkout_dir + \' && \' +

4条回答
  •  旧时难觅i
    2021-02-07 11:33

    Indeed, the BSD implementation of xargs doesn't have the -r flag (--no-run-if-empty). The GNU version in Linux has it.

    Here's one way to work around the issue in a way that works in both Linux and BSD:

    ... | (grep -v ^deploy || echo :) | xargs svn revert
    

    The grep ... || echo : in the middle will generate a line with a : in it in case the output of grep is empty. It's a bit dirty, because xargs will still run the command svn revert :. If your repository doesn't contain the file : then this should have no effect, so it can be acceptable. The : could be anything else, as long as there is no such file in your repository.

    Finally, as @tripleee pointed out, the grep ... || echo : must be enclosed within (...), because:

    the || has higher precedence than |, and thus terminates the (first) pipeline.

    Your code looks like a Python string. It will be more readable this way:

    kwargs = {
      'svn': svn_command,
      'dir': checkout_dir,
      'revno': options.revision,
    }
    cmd = "cd {dir} && {svn} st | awk -v r=1 '$2 ! ~ /deploy/ {{ print $2; r=0 }} END {{ r || print \":\" }}' | xargs {svn} revert && {svn} up -r {revno}".format(**kwargs)
    

    I made some changes to your original:

    • Moved the logic of the grep inside awk, as @tripleee suggested. Notice that since the grep hack is not needed anymore, there is also no more need to wrap within (...)
    • Dropped the tac, as I don't see the point in it
    • Dropped the -R from svn revert, because I don't think you need it

提交回复
热议问题