LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   bash command or function that doesn't change the error code (https://www.linuxquestions.org/questions/linux-newbie-8/bash-command-or-function-that-doesnt-change-the-error-code-4175695643/)

PeterPanic 05-26-2021 02:39 PM

bash command or function that doesn't change the error code
 
Hi!

I'm trying to write a bash function or command that will not alter the error level of the previous command.

My application: I wat to create a $PS1 that outputs the error level of the last command (green=OK=0, red=error!=0) in my prompt ($PS1) within a function or script that returns the stdout colored string, I can never manage to KEEP the error level as it was....

As soon as I create a bash function or command that sets the color to grreen/red (echo/printf), they always return "0" as their error level.

Even if I try things like that as "color.sh:
Code:

#!/bin/bash
errorLevel=$?
case "$1" in
    "black")          printf '\e[30m' ;;
    "d-red")          printf '\e[31m' ;;
    "d-green")        printf '\e[32m' ;;
    "brown")          printf '\e[33m' ;;
    "d-blue")          printf '\e[34m' ;;
    "magenta")        printf '\e[35m' ;;
    "cyan")            printf '\e[36m' ;;
    "l-gray")          printf '\e[37m' ;;
    "d-gray")          printf '\e[90m' ;;
    "red")            printf '\e[91m' ;;
    "green")          printf '\e[92m' ;;
    "yellow")          printf '\e[93m' ;;
    "blue")            printf '\e[94m' ;;
    "pink")            printf '\e[95m' ;;
    "sky")            printf '\e[96m' ;;
    "white")          printf '\e[97m' ;;
    *)                printf '\e[m'  ;;
 esac
exit $errorLevel

Afterwards, the error level will always be "0" ... :(

How can I write a function or command that does not change the error level ($?)?

smallpond 05-26-2021 04:06 PM

This is tricky. A bash script runs in a new, clean bash instance so it doesn't get the $? from the caller. A function runs in the same instance as the caller, but anything you do will set $?. This includes doing:

Code:

errorLevel=$?
Fortunately, the return value of the function can be set by the bash "return" command, so this works:

Code:

function preserve() {
  errorLevel=$?
  echo $errorLevel
  return $errorLevel
}

cat bazzle
cat: bazzle: No such file or directory
preserve
1
echo $?
1


PeterPanic 05-27-2021 12:27 PM

You saved my life (... and my error level :P ). Thanks a lot!


All times are GMT -5. The time now is 10:03 AM.