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.

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

2 Answers 2

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
3
  • 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. Apr 4, 2018 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. Apr 4, 2018 at 10:13
  • And I now see that in the edited post, there are indeed double quotes in the input file. Apr 5, 2018 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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .