How to access original command-line argument strin

2019-05-05 11:03发布

问题:

I'm trying to access the original command line argument string in Ruby (ie - not using the pre-split/separated ARGV array). Does anyone know how to do this? For example:

$> ruby test.rb command "line" arguments

I want to be able to tell if 'line' had quotes around it:

"command \"line\" arguments"

Any tips? Thanks in advance

回答1:

As far as I can tell, ruby is not removing those double-quotes from your command line. The shell is using them to interpolate the contents as a string and pass them along to ruby.

You can get everything that ruby receives like this:

cmd_line = "#{$0} #{ARGV.join( ' ' )}"

Why do you need to know what is in quotes? Can you use some other delimiter (like ':' or '#')?

If you need to, you can pass double-quotes to ruby by escaping them:

$> ruby test.rb command "\"line\"" arguments

The above cmd_line variable would receive the following string in that case:

test.rb comand "line" arguments


回答2:

I think it's unlikely, as far as I know that's all dealt with by the shell before it gets passed to the program.



回答3:

On Unix systems, the command line shell (Bash, csh, etc.) automatically converts such syntax into argument strings and sends them to the Ruby executable. For instance, * automatically expands to each file in a directory. I doubt there is a way to detect this, and I ask why you want to do so.



回答4:

This should help:

cmdline = ARGV.map{|x| x.index(/\s/) ? "\"#{x}\"":x}.join " "

Since shell groups the words inside quotes into one argument, we need to check if each argument has whitespace in it, and if it does, put quotes around it.

It still won't preserve wildcards (*), env variables ($VAR), and other stuff that shell expands before passing it to your script.

To be able to pass a command as it is, without expansions, you'd have to resort to passing it in through IO, like echo "ls *" | my_script.rb



回答5:

Ruby has a special module for this purpose.

http://ruby-doc.org/stdlib-1.9.3/libdoc/shellwords/rdoc/Shellwords.html

What you want is just:

require 'shellwords'
Shellwords.join ARGV[1..-1]

:p