winklerrr
winklerrr

Reputation: 14877

How to suppress function output in Bash?

I wrote a little helper to start an Android emulator which looks like this:

# START ANDROID EMULATION
android-sim () {
  if [[ -z "$1" ]]; then
    echo "No Android device supplied as argument!"
    return 1
  fi

  if [[ -d "$ANDROID_HOME" ]]; then
    cd "$ANDROID_HOME/emulator" &>/dev/null 
    ./emulator "@$1" &>/dev/null &
    cd - &>/dev/null 
  else
    echo "The variable ANDROID_HOME is not set to a correct directory!"
  fi
}

I tried to suppress all the generated output with &>/dev/null. For the emulator itself I also tried to put the execution in the background.

But when I run the function I still get the following output:

# before exeuction
[09:11:48] sandrowinkler:~ $ android-sim pixel-29
[1] 23217

# after execution, I closed the emulator via GUI
[09:11:55] sandrowinkler:~ $ 
[1]+  Done                    ./emulator "@$1" &> /dev/null  
(wd: /usr/local/share/android-sdk/emulator)
(wd now: ~)

According to this superuser post and this unix post I used the right way to silence the output. So what am I doing wrong here?

PS: I would also appreciate tips to improve my Bash code.

Upvotes: 1

Views: 82

Answers (2)

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19335

If the monitoring of the background job is not needed the double fork may be a solution.

 ( ./emulator "@$1" &>/dev/null & )

when the parent exit before the child process the child process is attached to process 1 so no more monitored by current shell.

also looking at the script, cd - could be avoided changing directory in the sub shell:

(
    cd "$ANDROID_HOME/emulator" 
    ./emulator "@$1" &
) &>/dev/null 

because current shell will not be affected by subshell change directory

Upvotes: 1

Miguel
Miguel

Reputation: 2219

You've done it correctly. That output is not from your script, but from the shell, displaying information about the background process (the PID, the done message and the working directory when in ends).

If you redirect the input externally, like this:

andoroid-sim foo > log.txt

and after execution you open log.txt, you'll see what actually your program outputed (and those messages won't be there, even if they appear in the console).

Upvotes: 1

Related Questions