bash if statement prints stuff to terminal

I am new to writing bash scripts, so I can't understand how to fix (remove) consoling of stuff that are inside if statement (see code below). Could someone tell me why it does stuff like that?

    if pgrep "Electron" -n
        then 
            killall Electron
        else        
            echo "Visual Studio Code is already closed"
    fi

2 answers

  • answered 2022-05-04 10:50 Tolis Gerodimos

    You could bash redirection https://www.gnu.org/software/bash/manual/html_node/Redirections.html


    if pgrep "Electron" -n > /dev/null
            then 
                killall Electron 
            else        
                echo "Visual Studio Code is already closed" 
        fi
    

    When you pass a linux command in the if statement, bash will run this command in order to check its exit code. The exit code of this command will be used in order to decide true or false. In bash 0 means true, any other exit code evaluates to false.

    So since bash execute the command, you will see its output in the terminal. In order to surpress the output, you can use redirection

  • answered 2022-05-04 10:51 Czaporka

    From man pgrep on MacOS:

    -q Do not write anything to standard output.

    So you can change your condition to:

    if pgrep -q "Electron" -n
        ...
    

    A more generic solution that should work with implementations of pgrep that do not support the -q option (e.g. on Ubuntu), as well as with any other tool, would be to redirect the process's standard output to /dev/null:

    if pgrep "Electron" -n >/dev/null
        ...
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum