gpt4 book ai didi

bash - 什么时候使用带有选项 -c 的 bash?

转载 作者:行者123 更新时间:2023-11-29 09:42:41 29 4
gpt4 key购买 nike

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

-c: If the -c option is present, then commands are read from the first non-option argument command_string. If there are arguments after the command_string, they are assigned to the positional parameters, starting with $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 -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 语法(<(...)),所以您不能使用默认使用 POSIX sh 的任何东西运行它,subprocess.Popen(..., shell=True) 就是这种情况。 ;使用 bash -c从而提供对功能的访问权限,而如果您自己不使用 FIFO 则无法使用这些功能。


顺便说一下,这不是唯一的方法:也可以使用 bash -s ,并在 stdin 上传递代码。下面,这不是从 Python 而是 POSIX sh( /bin/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

关于bash - 什么时候使用带有选项 -c 的 bash?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39904003/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com