bash - 如何在 linux [bash shell] 中传递 ' [单引号字符] 作为参数?

标签 bash command-line-arguments

我有 abc.py 文件,它接受参数 -p [password]-c [command]。 现在我可以按如下方式运行该文件:

./abc.py -p 'a!s!d!f' -c 'ifconfig'

a!s!d!f 是我的密码。由于密码包含 ! 字符,因此我必须将其作为 ' ' 中的参数发送。我尝试用 "" 发送它,但没有成功。

现在我想按如下方式运行此代码:

./abc.py -p 'a!s!d!f' -c './abc.py -p 'a!s!d!f' -c 'ifconfig''

我将 ./abc.py -p 'a!s!d!f' -c 'ifconfig' 作为 abc.py 的参数

问题是,我无法将 ' 字符作为参数发送给 abc.py

我需要将此 ' 字符作为输入发送。

我尝试使用 \ 转义字符:

./abc.py -p 'a!s!d!f' -c './abc.py -p \'a!s!d!f\' -c \'ifconfig\''

但不工作。我该怎么做呢?任何帮助将不胜感激。

最佳答案

您需要同时引用 '!:

./abc.py -p 'a!s!d!f' -c "./abc.py -p 'a!s!d!f' -c 'ifconfig'"

$ cat p.py
import sys
print sys.argv

在 Korn shell 中:

$ python p.py -p 'a!s!d!f' -c "./abc.py -p 'a!s!d!f' -c 'ifconfig'"
['p.py', '-p', 'a!s!d!f', '-c', "./abc.py -p 'a!s!d!f' -c 'ifconfig'"]

在 bash ! 中,仅当用单引号括起来时才进行特殊处理,因此可以这样做:

$ python p.py -p 'a!s!d!f' -c './abc.py -p '"'"'a!s!d!f'"'"' -c config'
['p.py', '-p', 'a!s!d!f', '-c', "./abc.py -p 'a!s!d!f' -c config"]

请注意,结果与用双引号引用整个字符串时不同:

$ python p.py -c "./abcy.py -p 'a\!s\!d\!f' -c 'ifconfig'"
['p.py', '-c', "./abcy.py -p 'a\\!s\\!d\\!f' -c 'ifconfig'"]

关于bash - 如何在 linux [bash shell] 中传递 ' [单引号字符] 作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16460207/

相关文章:

mysql - 加载数据 Infile MySQL 的 Bash 脚本

linux - while 循环中的 awk 命令问题

bash - 为什么有时当我在 bash 提示符下粘贴命令时,即使我不按 Enter,它也会执行?

bash - bash 中的 =~ 运算符支持哪些正则表达式语法?

来自参数字符串的 Python Optparse

java - 使用特定版本的 JRE 执行 JAR 文件

bash - 在 bash 中完成后台作业时通知

java - 将 CLA 转换为 Double

c# - 如何在控制台应用程序中隐藏输出(不是窗口)?

c++ - 从命令行向 C++ 传递参数