Search code examples
macosbashstderrcommand-substitution

Bash command substitution stdout+stderr redirect


Good day. I have a series of commands that I wanted to execute via a function so that I could get the exit code and perform console output accordingly. With that being said, I have two issues here:

1) I can't seem to direct stderr to /dev/null.

2) The first echo line is not displayed until the $1 is executed. It's not really noticeable until I run commands that take a while to process, such as searching the hard drive for a file. Additionally, it's obvious that this is the case, because the output looks like:

sh-3.2# ./runScript.sh
sh-3.2# com.apple.auditd: Already loaded
sh-3.2# Attempting... Enable Security Auditing ...Success

In other words, the stderr was displayed before "Attempting... $2"

Here is the function I am trying to use:

#!/bin/bash
function saveChange {
    echo -ne "Attempting... $2"
    exec $1
    if [ "$?" -ne 0 ]; then
        echo -ne " ...Failure\n\r"
    else
        echo -ne " ...Success\n\r"
    fi
}

saveChange "$(launchctl load -w /System/Library/LaunchDaemons/com.apple.auditd.plist)" "Enable Security Auditing"

Any help or advice is appreciated.


Solution

  • this is how you redirect stderr to /dev/null

    command 2> /dev/null
    

    e.g.

    ls -l 2> /dev/null
    

    Your second part (i.e. ordering of echo) -- It may be because of this you have while invoking the script. $(launchctl load -w /System/Library/LaunchDaemons/com.apple.auditd.plist)