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
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.
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.
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:
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:
The above
cmd_line
variable would receive the following string in that case:This should help:
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
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:
:p