0

How to make a code bellow as a general function to be used entire script in bash:

if [[ $? = 0 ]]; then 
    echo "success " >> $log
else echo "failed" >> $log
fi
Raid5
  • 51
  • 1
  • 5
  • You mean to execute this automatically after every command? – anubhava Oct 25 '13 at 11:05
  • Related and very useful: [What is the best way to write a wrapper function that runs commands and logs their exit code](http://stackoverflow.com/a/372120/1983854) – fedorqui Oct 25 '13 at 11:14

4 Answers4

2

You might write a wrapper for command execution:

function exec_cmd {
    $@
    if [[ $? = 0 ]]; then 
        echo "success " >> $log
    else 
        echo "failed" >> $log
    fi
}

And then execute commands in your script using the function:

exec_cmd command1 arg1 arg2 ...
exec_cmd command2 arg1 arg2 ...
...
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
0

If you don't want to wrap the original calls you could use an explicit call, like the following

function check_success {
    if [[ $? = 0 ]]; then 
        echo "success " >> $log
    else echo "failed" >> $log
    fi
}



ls && check_success

ls non-existant
check_success
Arialdo Martini
  • 4,427
  • 3
  • 31
  • 42
0

There's no really clean way to do that. This is clean and might be good enough?

PS4='($?)[$LINENO]'
exec 2>>"$log"

That will show every command run in the log, and each entry will start with the exit code of the previous command...

Mark Reed
  • 91,912
  • 16
  • 138
  • 175
0

You could put this in .bashrc and call it whenever

function log_status { [ $? == 0 ] && echo success>>/tmp/status || echo fail>>/tmp/status }

If you want it after every command you could make the prompt write to the log (note the original PS1 value is appended).

export PS1="\$([ \$? == 0 ] && echo success>>/tmp/status || echo fail>>/tmp/status)$PS1"

(I'm not experienced with this, perhaps PROMPT_COMMAND is a more appropriate place to put it)

Or even get more fancy and see the result with colours.

I guess you could also play with getting the last executed command:

Community
  • 1
  • 1
jozxyqk
  • 16,424
  • 12
  • 91
  • 180