Shorten or merge multiple lines of `&> /dev/null &`

Solution 1:

The part &> /dev/null means output redirection. You can redirect multiple commands to the same file by grouping them into a block:

#! /bin/bash
{
google-chrome &
lantern &
xdg-open . &
emacs  &
code ~/Programs/ &
xdg-open ~/Reference/topic_regex.md &
} &> /dev/null

The same thing, however, cannot be used to start individual commands in the background (&). Putting & after the block would mean running the whole block as a single script in the background.

Solution 2:

I wrote a function and put it into my .bashrc to run things detached from my terminal:

detach () 
{ 
    ( "$@" &> /dev/null & )
}

... and then:

detach google-chrome
detach xdg-open ~/Reference/topic_regex.md

And because I'm lazy, I also wrote a shortcut for xdg-open:

xo () 
{ 
    for var in "$@"; do
        detach xdg-open "$var";
    done
}

Because xdg-open expects exactly one argument, the function xo iterates over all given arguments and calls xdg-open for each one separately.

This allows for:

detach google-chrome
xo . ~/Reference/topic_regex.md

Solution 3:

You could redirect the output for all subsequent commands with

exec 1>/dev/null
exec 2>/dev/null

Solution 4:

You could create a loop and give it the commands as arguments:

for i in google-chrome "xdg-open ." "code ~/Programs/"; do
  $i &
done &>/dev/null

Note that this way exactly as with the subshell approach with curly braces it’s possible to sum up the outputs and redirect all of them at once.