1

I want to run command in Rust? I know Command::new(), but I have problems with running this command: nohup gdx-open ~/Documents &.

2
  • 3
    What problems do you have? Commented Sep 3, 2021 at 7:07
  • 1
    & is part of the shell syntax, it makes no sense in a command. And nohup is also a shell thing (it protects the wrapped command against SIGHUP). Commented Sep 3, 2021 at 7:26

1 Answer 1

5

nohup and & are shell-specific constructs that tell your shell not to wait for the command to finish. They are not really part of your command at all, so what you want is:

let handle = Command::new("gdx-open")
                    .args(&["~/Documents"])
                    .spawn()
                    .unwrap();

If instead you wanted to wait for the command to finish before proceeding, you would use:

let result = Command::new("gdx-open")
                    .args(&["~/Documents"])
                    .status()
                    .unwrap();

or

let output = Command::new("gdx-open")
                    .args(&["~/Documents"])
                    .output()
                    .unwrap();

Moreover, the ~ is also a shell-specific construct which may or may not be understood by the command you're trying to run. It means "this user's home directory", which you can get from the HOME environment variable using std::env::var:

let path = format!(
    "{}/Documents", 
    std::env::var ("HOME").unwrap_or_else (|_| "".into()));
let handle = Command::new("gdx-open")
                    .args(&[&path])
                    .spawn()
                    .unwrap();

And BTW, ~/Documents is a special path, part of the XDG user directories specification. Its actual location is platform-dependent and language-dependent (i.e. it gets translated depending on the user's configuration). It can also be overridden by the user. You might want to look at the directories crate to get the correct value:

use directories::UserDirs;
let dirs = UserDirs::new();
let path = dirs
    .and_then (|u| u.document_dir())
    .unwrap();
let handle = Command::new("gdx-open")
                    .args(&[path])
                    .spawn()
                    .unwrap();
Sign up to request clarification or add additional context in comments.

3 Comments

While nohup can be a shell builtin, and is nowadays mostly a workaround for shell behaviour (that closing a shell SIGHUPs its children, specifically the entries in its job table), technically it's not strictly shell-specific. It is completely useless here though.
The problem is that File Manages closes, after completing the command.
The ~ is also a shell thing, that expands to the home directory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.