Score:0

How to check if last k commands ran successfully

cn flag

I am running a couple of bash commands and want to check if all of them ran successfully at the end. How should I go about this?
This is what I tried.

$ man # command 1 with exit status 1
What manual page do you want?

$ res1=$? # command 2 with exit status 0
# this also stores exit code of previous code i.e 1

$ res2=$? # storing exit code of previous command i.e 0

# Now I want to check if all previous commands worked fine with their exit codes
$ echo $res1 && $res
1
0: command not found

What is incorrect with my current approach. Or What should be the right thing to do? Is there a better way to generalize it for last k commands.
Thanks in advance.

guiverc avatar
cn flag
You `echo $res` but then ask `$res` to be executed as a command? thus 'command not found' is valid as I'm not aware of a 0 command either. The `&&` as you specified it breaks the commands and executes the following ONLY IF the first part executed successfully; thus `$res` was attempted to be executed; but 0 is invalid... thus error
Score:0
in flag

I had some problems as this too

id solve my problem in this way

first, I wrote a function that checks the status of the command I run in my script


function show_process_status() {
    if [ $? == 0 ]; then 
        echo $1
    else
        echo $2
        break
    fi
}

then in my script, I call this function after any command that I run, for example :

function update_system (){
    echo "start updating system"
    sudo apt-get update -y
    show_process_startus "repos updated successful" "An error occurred on updating repos"
    if [[ $1 == "full" ]]; then
        sudo apt-get dist-upgrade -y
        show_process_startus "system updated successful" "An error occurred on updating systems"
    elif [[ $1 == "fix" ]]; then 
        sudo apt-get update --fix-missing
        show_process_startus "update fix missing successful" "An error occurred on fix missing"
        sudo apt-get update
    fi
}

in the show_process_status function I get two-argument the first one is printed when the code run and exits successfully and the second one is used when the command exit is unsuccessful.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.