I wrote a simple script that writes all given arguments to a single text file, separated by newline. I'd like to pass a list of files to it using OptionParser. I would like to add a couple of files using wildcards like /dir/*
.
I tried this:
opts = OptionParser.new
opts.on('-a', '--add FILE') do |s|
puts "DEBUG: before #{s}"
@options.add = s
puts "DEBUG: after #{@options.add}"
end
...
def process_arguments
@lines_to_add = Dir.glob @options.add
end
Put when I add files like this:
./script.rb -a /path/*
I always get only the first file in the directory. All the debug outputs show only the first file of directory, and it seems as if OptionParser does some magic interpretations
Does anyone know how to handle this?
You didn't mention which operating system you are using (it matters).
On Windows, whatever you type on the command line gets passed to the program without modification. So if you type
./script.rb -a /path/*
then the arguments to the program contain "-a"
and "/path/*"
.
On Unix and other systems with similar shells, the shell does argument expansion that automatically expands wildcards in the command line. So when you type the same command above, the shell looks to find the files in the /path/*
directory and expands the command line arguments before your program runs. So the arguments to your program might be "-a"
, "/path/file1"
, and "/path/file2"
.
An important point is that the script cannot find out whether argument expansion happened, or whether the user actually typed all those filenames out on the command line.