How to get parameters when starting the program?

My code looks like this:

fn main(){
    let mut args: Vec<OsString> = env::args_os().collect();
    println!("{:?}",args);
}

The startup parameter is a file path with *, which is expected to obtain the file path with *, but env:: argsos helps me convert it into a real path. What should I do to directly obtain the path with *?

it's likely your shell is parsing and expanding the glob, not the Rust program. If you want to pass a literal * in most shells you can use single quotes: '*'

6 Likes

This result is consistent with the comment of this function, but I don't know whether there are other methods to meet my needs.

Note that “the shell expands arguments with glob patterns” means there’s nothing your program can do to obtain the *. It’s not the env::args_os() function that expands the *, it’s happening before your program is even started. “The shell” is something like sh or bash or zsh, that’s the application running in your terminal by default when you start it, where you type the commands, and the same application that figures out from the command name you type what executable should be run, etc…

Asking for methods of how to make a Rust program get the uninterpreted arguments (with * unexpanded) is maybe a bit like asking how to figure out whether or not the user starting your program had a typo in the command that they corrected (using backspace), whether they used an alias (that the shell interpreted/translated) when calling the command, or how fast they typed it. All things that happen before the start of your program, and outside of the control of your program, i.e. information it simply doesn’t receive to begin with.


As mentioned in the previous answer the way to get a * passed to your program is to call it differently. Either through a shell that doesn’t expand the *s to begin with, or by some form of "escaping" such as the suggested approach to wrap the argument in single quotes '…' (the shell will remove the quotes, but typically in popular shells, single quotes mean that the contents of the quoted string should not be expanded/interpreted further).


In zsh there’s also the noglob command which could be useful. If you define an alias foo='noglob foo' for your executable foo, then glob patterns will never be expanded as long as that alias is used. I’m not sure if there’s an equivalent for other shells such as bash.

2 Likes