简体   繁体   English

通过连字符将bash传递值

[英]passing bash a value with leading hyphen

I have a bash command that requires a string value after "-v". 我有一个bash命令,要求在“ -v”之后有一个字符串值。 When this string value has a leading "-", bash tries to interpret it as a new option of the bash command rather than the value I'm trying to give for -v. 当此字符串值带有前导“-”时,bash尝试将其解释为bash命令的新选项,而不是我尝试提供的-v值。 Is there a way I can escape this leading hyphen? 有没有办法可以摆脱这种领先的连字符? I tried -v -- -myValue but then it tells me "option '-v' needs a parameter." 我尝试了-v -- -myValue但随后它告诉我“选项'-v'需要一个参数”。

The command is calling a ruby file. 该命令正在调用ruby文件。 I think this is the meaningful part of the ruby code for the purposes of this question: 对于这个问题,我认为这是Ruby代码中有意义的部分:

opts = Trollop::options do
  opt :method, "Encrypt or Decrypt", :short => "m", :type => :string, :default => "decrypt"
  opt :value, "Value to Decrypt or Encrypt", :short  => "v", :type => :string, :default => ""
end

There's two conventional ways to specify arguments, but these are not enforced at the shell level, they're just tradition: 有两种指定参数的常规方法,但是这些方法不是在Shell级别强制执行的,它们只是传统方法:

-v xxxx
--value=xxxx

Now it's sometimes possible to do: 现在有时可以执行以下操作:

-vxxxx

If you have a value with a dash and it's not being interpreted correctly, do this: 如果您的值带有破折号并且无法正确解释,请执行以下操作:

--value=-value
cmd -v '-string value with leading dash'

edit 编辑

$ cat ~/tmp/test.sh
 #!/bin/bash
 str=
 while getopts "v:" opt; do
 case "$opt" in
    v) str=$OPTARG;;
 esac
 done
 shift $(( OPTIND -1 ))

 echo "option was '$str'"

simple test file, my bash is GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu) 简单的测试文件,我的bash是GNU bash,版本4.3.11(1)-发行版(x86_64-pc-linux-gnu)

results: 结果:

chris@druidstudio:~⟫ ~/tmp/test.sh -v string
  option was 'string'
chris@druidstudio:~⟫ ~/tmp/test.sh -v -string
  option was '-string'
chris@druidstudio:~⟫ ~/tmp/test.sh -v '-string'
  option was '-string'

so, maybe, the bash script handling your options is not written correctly, or you have an early version of bash. 因此,也许处理您的选项的bash脚本编写不正确,或者您使用的bash早期版本。 As I answered in another of these silly questions earlier, clairvoyance is not one of my skills. 正如我之前在另一个愚蠢的问题中回答的那样,千里眼不是我的技能之一。 So, be a good chap and possibly give us, the people you are asking for help from, the pertinent information (as you state, your script is failing at the bash level, not at the ruby level, so why bother to post a ruby script?) 因此,请做好准备,并可能给我们您要寻求帮助的人员,相关信息(正如您所说的那样,您的脚本在bash级别而不是在ruby级别失败,所以为什么要麻烦发布一个ruby脚本?)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM