Milister
Milister

Reputation: 658

Multiple variables in a CASE statement-BASH

st file

failed" "aa" "2018-04-03T17:43:38Z" "2018-04-03T18:43:38Z"

I have code which reads line into varaible and compares it with differenr values ("succeded","failed","aborted") and writes appropriate output.

while read -r status name startdate enddate; do


case "$status" in
 "\"aborted\"")
echo "Job " $name "aborted"
;;
 "\"failed\"")
echo "Job " $name "failed" " In project Demo"
;;
 "\"succeeded\"")
echo "Job " $name "success"
;;
#*) echo 0 + $name
esac
exit 0
done<st.txt

Now want to add another condition in existing case statement: compare two dates and if difference between them is greather than 5 minutes and status "aborted" print "aborted-long running", if time difference is less than 5 minutes and status "aborted" then just print "aborted" for other conditions no need to change anything

i imported another variable elapsed which will calculate difference between start and end date

is it possible to put this variable (together with $status in case statement)

i introduced elapsed variable in code but don't know how to integrate with existing case

while read -r status name startdate enddate; do

startdate=${startdate//\"/}
stime=$(date -d "${startdate/T/ }" +%s)
enddate=${enddate//\"/}
etime=$(date -d "${enddate/T/ }" +%s)
let elapsed=etime-stime

case "$status" in
 "\"aborted\"")
echo "Job " $name "aborted"
;;
 "\"failed\"")
echo "Job " $name "failed" 
;;
 "\"succeeded\"")
echo "Job " $name "success"
;;
*) echo 0 + $name
esac
exit 0


done<st.txt

Upvotes: 0

Views: 4897

Answers (2)

glenn jackman
glenn jackman

Reputation: 247142

Just add some more code to the aborted case branch:

case "$status" in
    '"aborted"')
        [[ $elapsed -gt 300 ]] && extra="-long running" || extra=""
        echo "Job $name aborted $extra"
        ;;
    '"failed"')
        echo "Job $name failed" 
        ;;
    '"succeeded"')
        echo "Job $name success"
        ;;
    *) echo "0 + $name" ;;
esac

I would encourage you to use indentation on your code.

Also, quote your variables

Upvotes: 4

Milister
Milister

Reputation: 658

Multiple IF statements: i thought it's more complicated

   if [ "$status" == "\"aborted\"" ] && [ "$elapsed" -gt 300 ]; then echo "Long Running Process-Demo"
    elif  [ "$status" == "\"aborted\"" ] && [ "$elapsed" -lt 300 ]; then echo "Aborted-Demo"
    elif  [ "$status" == "\"failed\"" ]; then echo "Job" $name "failed-Demo"
    elif  [ "$status" == "\"succeeded\"" ]; then echo "Job" $name "Succeded"
    fi

Upvotes: 0

Related Questions