Bash – Suppressing output to STDOUT

bashcommand lineerrorscriptxcode

I've written a script for fresh macOS installs that installs Homebrew, Cask, and a bunch of apps I like, along with creating a .vimrc file.

Thanks to an answer by daniel Azuelos (located here: Best way to check in bash if Command Line Tools are installed?), a part of the script checks to see if Xcode command-line-tools are installed.

When command-line-tools are not installed, this error gets displayed to the user:

xcode-select: error: unable to get active developer directory, use `sudo xcode-select --switch path/to/Xcode.app` to set one (or see `man xcode-select`)

I'm hoping someone can help me suppress this output.

The function that is ran to do command-line-tools check is:

function check_clt() {
    if type xcode-select >&- && xpath=$( xcode-select --print-path ) && test -d "${xpath}" && test -x "${xpath}" ; then
        echo ""
        echo "The required Xcode command-line-tools are already installed! Moving on!"
        sleep 3
    else
        instructions
        sleep 45
        xcode-select --install
    fi
}

I believe I can use 2 > /dev/null to suppress the error, but I'm not sure in the function where should it go? I've put it before each && in the if statement, but the error message still appeared.

Using Nimesh's suggestion, I've edited the function:

function check_clt() {
if type xcode-select 2>/dev/null >&- && xpath=$( xcode-select --print-path ) 2>/dev/null && test -d "${xpath}" 2>/dev/null && test -x "${xpath}" 2>/dev/null ; then
    echo ""
    echo "The required Xcode command-line-tools are already installed! Moving on!"
    sleep 3
else
    instructions 2>/dev/null
    sleep 45
    xcode-select --install
fi

}

Running the script still produces the error to the user:

Last login: Tue Sep  4 20:40:13 on ttys000
vimusrs-Mac:~ vimusr$ cd Desktop/
vimusrs-Mac:Desktop vimusr$ chmod +x mai.sh 
vimusrs-Mac:Desktop vimusr$ ./mai.sh 
xcode-select: error: unable to get active developer directory, use `sudo xcode-select --switch path/to/Xcode.app` to set one (or see `man xcode-select`)

Best Answer

Turns out the xpath=( xcode-select --print-path ) line in the if statement of the original function was the problem. Additionally, once I got the error message suppressed, I noticed there was an unnecessary stdout message, so I decided to suppress that as well.

I was able to suppress the stderror and stdout messages by changing the function to the following:

function check_clt() {
    if type xcode-select >/dev/null 2>&1 >&- && xcode-select -p >/dev/null 2>&1 && test -d $(xcode-select -p) >/dev/null 2>&1 && test -x $(xcode-select -p) >/dev/null 2>&1; then
        echo ""
        echo "The required Xcode command-line-tools are already installed! Moving on!"
        sleep 3
    else
        instructions
        sleep 45
        xcode-select --install
    fi
}