且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

解析命令行参数作为通配符

更新时间:2023-11-29 19:55:28

您正在使用的操作系统(它很重要)。你没有提到

在Windows上,不管你在命令行中输入被传递给程序而无需修改。所以,如果你键入

  ./ script.rb -a /路径/ *

那么参数程序包含 - 一个/路径/ * 。 p>

在Unix和其他系统类似的壳,壳做的参数扩展的,在命令行自动扩展通配符。所以,当你键入相同的命令以上时,的的外观来查找 /路径/ * 目录中的文件之前扩大了命令行参数你的程序运行。所以,争论到您的程序可能是 - 一个/路径/文件1/路径/文件2

这是很重要的一点是,该脚本无法找到论据​​是否扩大发生,或者用户是否实际键入所有这些文件名了命令行上。

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.