Quantcast
Channel: How to cleanly launch a GUI app via the Terminal? - Ask Ubuntu
Viewing all articles
Browse latest Browse all 12

Answer by Roger Pate for How to cleanly launch a GUI app via the Terminal?

$
0
0

The mysterious ampersand "&" suffix, seems to cause the terminal to put the process into the background... (but I'm not sure what happens there).

It does, and is often what you want. If you forget to use &, you can suspend the program with ctrl-z then place it in the background with the bg command — and continue to use that shell.

The process' stdin, stdout, and stderr are still connected to the terminal; you can redirect those from/to /dev/null or any other file (e.g. save an output log somewhere), as desired:

some-program </dev/null &>/dev/null &
# &>file is bash for 1>file 2>&1

You can see the process in jobs, bring it back to the foreground (fg command), and send it signals (kill command).

Some graphical programs will detach from the terminal; if that's the case, when you run the command "normally" you'll notice it starts the graphical program and "exits".


Here's a short script, you can place it in ~/bin, which I named runbg:

#!/bin/bash
[ $# -eq 0 ] && {  # $# is number of args
  echo "$(basename $0): missing command" >&2
  exit 1
}
prog="$(which "$1")"  # see below
[ -z "$prog" ] && {
  echo "$(basename $0): unknown command: $1" >&2
  exit 1
}
shift  # remove $1, now $prog, from args
tty -s && exec </dev/null      # if stdin is a terminal, redirect from null
tty -s <&1 && exec >/dev/null  # if stdout is a terminal, redirect to null
tty -s <&2 && exec 2>&1        # stderr to stdout (which might not be null)
"$prog" "$@" &  # $@ is all args

I look up the program ($prog) before redirecting so errors in locating it can be reported. Run it as "runbg your-command args..."; you can still redirect stdout/err to a file if you need to save output somewhere.

Except for the redirections and error handling, this is equivalent to htorque's answer.


Viewing all articles
Browse latest Browse all 12

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>