Building off of ngoozeff
's answer, if you want to make a command run completely in the background (i.e., if you want to hide its output and prevent it from being killed when you close its Terminal window), you can do this instead:
cmd="google-chrome";
"${cmd}" &>/dev/null & disown;
&>/dev/null
sets the command’s stdout
and stderr
to /dev/null
instead of inheriting them from the parent process. &
makes the shell run the command in the background. disown
removes the “current” job, last one stopped or put in the background, from under the shell’s job control.In some shells you can also use &!
instead of & disown
; they both have the same effect. Bash doesn’t support &!
, though.
Also, when putting a command inside of a variable, it's more proper to use eval "${cmd}"
rather than "${cmd}"
:
cmd="google-chrome";
eval "${cmd}" &>/dev/null & disown;
If you run this command directly in Terminal, it will show the PID of the process which the command starts. But inside of a shell script, no output will be shown.
Here's a function for it:
#!/bin/bash
# Run a command in the background.
_evalBg() {
eval "$@" &>/dev/null & disown;
}
cmd="google-chrome";
_evalBg "${cmd}";