何时使用带有选项 -c 的 bash?

ima*_*hat 4 bash

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

-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
Run Code Online (Sandbox Code Playgroud)

Cha*_*ffy 5

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
Run Code Online (Sandbox Code Playgroud)

在这里,因为我们使用的是仅 bash 语法 ( <(...)),所以您无法使用默认使用 POSIX sh 的任何内容来运行此语法, ; 就是这种情况subprocess.Popen(..., shell=True)。因此, usingbash -c提供了对如果不亲自使用 FIFO 就无法使用的功能的访问。


顺便说一句,这不是唯一的方法:还可以使用bash -s, 并在标准输入上传递代码。/bin/sh下面,这不是通过 Python 而是通过 POSIX sh (同样不保证可用<(...))完成的:

#!/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
Run Code Online (Sandbox Code Playgroud)