Bash function to automatically run a command in background and disown

Viewed 815

I'm trying to make a function in my bashrc that would allow me to launch any command and automatically disown it.

e.g. launch ./myprogram or launch xdg-open myfolder

I've been used to do that many times command ; Ctrl+Z ; bg ; disown and would like to simply create a shortcut of these steps.

However I don't know how to embed the action of Ctrl+Z in a bash script. I've seen that its action is SIGTSTP, but I'm really lost as to how incorporate that in a bash function.

2 Answers

You can run the command in background directly instead of stopping it and then running it in the background. Use the &:

$ cat > launch
#! /bin/bash
"$@" & disown

Ctrl + d

$ chmod u+x ./launch

For posterity and othe people passing by, here is the bash function I made :

 launch()
{
"$@" > /dev/null 2>&1 & disown
}
  • "$@" takes every arguments given in the prompt as one
  • > /dev/null 2>&1 redirects every output (stout and stderr) to dev/null which effectively delete them automatically, so that it doesn't appear on the shell
  • & runs the command in background, meaning it will let you input other commands in the shell
  • disown , as the name implies will lake it so that the process is no longer bound to the shell and you cans safely close the shell without it closing the process at the same time.
Related