1
st.txt

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

   while read status name date; do
    case "$status" in
    'aborted')
        echo -1
        ;;
    "failed")
        echo -1
        ;;
    'succeeded')
        echo 0
        ;;
    *)
        echo 0
    esac
    exit 0
done < st.txt

But I always get 0 as the output.

  • Is there only one line in st.txt? – Arkadiusz Drabczyk Apr 3 '18 at 20:12
  • yes, it is, only one – Milister Apr 3 '18 at 20:16
  • What is the contents of st.txt? – Kusalananda Apr 4 '18 at 5:44
1

You should replace "failed" with "\"failed\"". It should be:

while read status name date; do
    case "$status" in
        'aborted')
            echo -1
            ;;
        "\"failed\"")
            echo -1
            ;;
        'succeeded')
            echo 0
            ;;
        *) echo 0
    esac
    exit 0
done<st.txt

Also consider using read with -r.

There is also an easier way to do what you want:

if [ "$(cut -d ' ' -f1 st.txt)" = "\"failed\"" ]
then
    printf -- "-1\n"
fi
  • Why is it necessary here to include the quotes in the matching expression? If I understand your solution correctly, this is the same as writing '"failed"', and this in turn would only make sense if there are also quotes around failed in st.txt. This is unlikely, since succeeded and aborted also don't have quotes. – user1934428 Apr 4 '18 at 7:04
  • 1
    Yes, it would be the same as writing '"failed"'. You're right that if OP also checked for "succeeded"" or "aborted" he would have to escape double quotes. Additional problem is that OP reads status, name and date but only uses status. – Arkadiusz Drabczyk Apr 4 '18 at 10:13
  • And I now see that in the edited post, there are indeed double quotes in the input file. – user1934428 Apr 5 '18 at 9:59
0

Another solution is to add single quotes around the double-quoted strings:

while read status name date; do
    case "$status" in
        '"aborted"')
             echo -1
             ;;
        '"failed"')
             echo -1
             ;;
        '"succeeded"')
             echo 0
             ;;
        *)
             echo 0
    esac
    exit 0
done < st.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.