【问题标题】:when to use bash with option -c?何时使用带有选项 -c 的 bash?
【发布时间】:2016-10-07 04:32:51
【问题描述】:

我正在尝试更好地理解 bash 的 -c 选项。手册页说:

-c:如果存在 -c 选项,则从第一个非选项参数 command_string 中读取命令。如果 command_string 后面有参数,则将它们分配给位置参数,从 $0 开始。

我无法理解这意味着什么。

如果我在使用和不使用 bash -c 的情况下执行以下命令,我会得到相同的结果(来自http://www.tldp.org/LDP/abs/html/abs-guide.html 的示例):

$ set w x y z; IFS=":-;"; echo "$*"
w:x:y:z
$ bash -c 'set w x y z; IFS=":-;"; echo "$*"'
w:x:y:z

【问题讨论】:

标签: bash


【解决方案1】:

bash -c你已经在运行 bash 时就没那么有趣了。另一方面,考虑从 Python 脚本运行 bash 代码的情况:

#!/usr/bin/env python
import subprocess
fileOne='hello'
fileTwo='world'

p = subprocess.Popen(['bash', '-c', 'diff <(sort "$1") <(sort "$2")',
                      '_',     # this is $0 inside the bash script above
                      fileOne, # this is $1
                      fileTwo, # and this is $2
                     ])
print p.communicate() # run that bash interpreter, and print its stdout and stderr

这里,因为我们使用 bash-only 语法 (&lt;(...)),所以你不能使用任何默认使用 POSIX sh 的东西来运行它,subprocess.Popen(..., shell=True) 就是这种情况;因此,使用 bash -c 可以访问如果不亲自使用 FIFO 就无法使用的功能。


顺便说一句,这不是唯一的方法:也可以使用bash -s,并在标准输入上传递代码。下面,这不是来自 Python,而是来自 POSIX sh(/bin/sh,同样不能保证&lt;(...) 可用):

#!/bin/sh

# ...this is POSIX sh code, not bash code; you can't use <() here
# ...so, if we want to do that, one way is as follows:

fileOne=hello
fileTwo=world

bash -s "$fileOne" "$fileTwo" <<'EOF'
# the inside of this heredoc is bash code, not POSIX sh code
diff <(sort "$1") <(sort "$2")
EOF

【讨论】:

    【解决方案2】:

    如何在 BASH shell 之外执行 BASH 代码

    答案是,使用-c 选项,它使BASH 执行作为参数传递给-c 的任何内容。

    所以,是的,这就是这个选项的目的,任意执行 BASH 代码,但只是以另一种方式。

    【讨论】:

      【解决方案3】:

      -c 选项在 bash 由另一个程序启动时发现其最重要的用途,尤其是当要执行的代码可能或确实包括重定向、管道、shell 内置函数、shell 变量分配和 /或重要的列表。在将/bin/sh 作为bash 别名的POSIX 系统上,它特别支持C 库的system() 函数。

      在不使用-c 的情况下在 fork / exec 之上实现等效行为要复杂得多,尽管并非完全不可能。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-11
        • 1970-01-01
        • 2021-12-19
        • 1970-01-01
        • 1970-01-01
        • 2012-11-11
        • 1970-01-01
        • 2016-04-01
        相关资源
        最近更新 更多