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

时间:2013-05-09 11:01:26

标签: 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\''

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

2 个答案:

答案 0 :(得分:2)

您需要引用'!

./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'"]

答案 1 :(得分:1)

在Bash中(在POSIX shell standard之后),单引号按字面意思保留每个字符,这意味着无法在单引号内转义内容。您的选择是:

  1. 通过将不同引用的字符串放在一起来连接它们:

    ./abc.py -c "./abc.py -p '"'a!s!d!f'"' -c 'ifconfig'"
    
  2. 使用双引号并转义!个字符:

    ./abc.py -c "./abcy.py -p 'a\!s\!d\!f' -c 'ifconfig'"
    
相关问题