I have a bash command that requires a string value after "-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. Is there a way I can escape this leading hyphen? I tried -v -- -myValue
but then it tells me "option '-v' needs a parameter."
The command is calling a ruby file. I think this is the meaningful part of the ruby code for the purposes of this question:
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:
-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'
$ 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)
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. 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?)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.