How to access original command-line argument strin

2019-05-05 11:19发布

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

5条回答
手持菜刀,她持情操
2楼-- · 2019-05-05 11:25

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楼-- · 2019-05-05 11:36

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楼-- · 2019-05-05 11:37

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
查看更多
再贱就再见
5楼-- · 2019-05-05 11:40

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

查看更多
聊天终结者
6楼-- · 2019-05-05 11:41

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

查看更多
登录 后发表回答