Monday, October 25, 2021

[SOLVED] How can I prevent "type" stdout from appearing while running my script?

Issue

I am currently working on a script that needs to check if a program is installed when it first starts up. If the program is not present, the script will proceed with doing whatever is necessary for the installation of the program. I have tried the following so far:

program_exist=$( type "someprogram" | grep "not found" )
if ! "$someprogram_exist"; then
        do some stuff
fi

program_exist=$( type "someprogram" 2>&1 >/dev/null | grep "not found" )
if ! "$someprogram_exist"; then
        do some stuff
fi

but each time I run this, I am always met with the following message:

./some_program.sh: line 8: ./some_program.sh: line 7: type: someprogram: not found: No such file or directory

Is there a way to check for the existence of a program without having it display the ./some_program.sh: line 8: ./some_program.sh: line 7: type: someprogram: not found: No such file or directory message each time?


Solution

Simply try this :

if ! type someprogram &>/dev/null; then
    do_some_stuff
fi

or shorter :

type someprogram &>/dev/null || do_some_stuff


Answered By - Gilles Quenot