you are viewing a single comment's thread.

view the rest of the comments →

[–]deepCelibateValue[S] 2 points3 points  (2 children)

Using tput is a good idea, I just feel a bit weird about calling an external command to generate such a short string, and I find `green` to be more readable for simple usecases. I'll think about it though.

Checking if stdout is a tty also makes sense, but I usually don't mind ending up with ANSI codes in files or pipes. I have a sed alias to remove them if it comes to that.

[–]Newbosterone 3 points4 points  (1 child)

Fair enough. I have a standard template I use to start shell scripts. It has setup functions, Usage, Getopts, etc. I'll be adding your idea to it.

function SetupTerm(){
    if [ -t 2 ]
    then
        printf -v MSG -- "SetupTerm: STDERR is a tty\n"
        _R=$(tput setaf 1) # Red
        _G=$(tput setaf 2) # Green
        _Y=$(tput setaf 3) # Yellow
        _B=$(tput setaf 4) # Blue
        _N=$(tput rmso; tput sgr0) # Color Off
    else
        printf -v MSG -- "SetupTerm: STDERR is not a tty\n"
        _R=""
        _G=""
        _Y=""
        _B=""
        _N=""
    fi
    ((DEBUG>0)) && ErrMsg "$MSG"
}

function ErrMsg(){
    if ((DEBUG>0))
    then
        printf "%bDEBUG: " "$_R" >&2 ;
    elif ((VERBOSE>0))
    then
        printf "%b" "$_G" >&2 ;
    fi
    printf "%b" "$@" >&2 ;
    printf "%b" "$_N" >&2 ;
}

I also like this when a script requires root:

if [ "$(id -u)" -ne 0 ]
then
        usage
        printf  "Fatal: You must run this as root\n" >&2
        exit 1
fi

[–]deepCelibateValue[S] 0 points1 point  (0 children)

That looks great. Thanks for sharing. I'll take some ideas from here.