Question

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.

Était-ce utile?

La 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)

Autres conseils

The first echo line is displayed later because it is being execute second. $(...) will execute the code. Try the following:

#!/bin/bash
function saveChange {
    echo -ne "Attempting... $2"
    err=$($1 2>&1)
    if [ -z "$err" ]; then
        echo -ne " ...Success\n\r"
    else
        echo -ne " ...Failured\n\r"
        exit 1
    fi
}

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

EDIT: Noticed that launchctl does not actually set $? on failure so capturing the STDERR to detect the error instead.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top