How to access the source line of a command line argument in Ruby?

I am trying to access the source line of a command line argument in Ruby (i.e. do not use a pre-partitioned / partitioned ARGV array). Does anyone know how to do this? For instance:

$> ruby test.rb command "line" arguments 

I want to find out if there are lines in it:

 "command \"line\" arguments" 

Any tips? thanks in advance

+4
source share
5 answers

As far as I can tell, ruby ​​does not remove these double quotes from the command line. The shell uses them to interpolate the contents as a string and pass them along with ruby.

You can get everything that Ruby gets as follows:

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

Why do you need to know what is in quotation marks? Can you use any other delimiter (e.g. ':' or '#')?

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

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

The above cmd_line variable will receive the following line in this case:

 test.rb comand "line" arguments 
+6
source

I think this is unlikely, as far as I know, that everything is with the shell before it is passed to the program.

+2
source

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

+2
source

This should help:

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

Since the shell groups the words inside the quotation marks into one argument, we need to check whether each argument has a space in it, and if so, put the quotation marks around it.

It still does not save wildcards (*), env variables ($ VAR), and other stuff that the shell expands before passing them to your script.

To be able to transfer the command as is, without extensions, you will have to resort to transferring it through IO, for example echo "ls *" | my_script.rb echo "ls *" | my_script.rb

0
source

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 simple:

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

: R

0
source

Source: https://habr.com/ru/post/1311741/


All Articles