Akendo
Akendo

Reputation: 2289

Why does this *normal* string compare failed in bash?

I have a string, like this:

DayOfWeek=$(date +%A|tr -d '\n') echo $DayOfWeek Montag

I wish to compare the result of the command with a string. Just like this:

[ $DayOfWeek == "Monday" ] && echo True But the result was anytime false.

Here some more attempts:

[ "$DayOfWeek" == "Monday" ] && echo True [ $(date +%A|tr -d '\n') == "Monday" ] && echo True [ $(date +%A|tr -d '\n') == "Monday" ] && echo True [ $(date +%A|tr -d '\n') == 'Monday' ] && echo True [ "$(printf "%s" "$DayOfWeek")" == "Monday" ] && echo True [ "$(date +%A|tr -d '\n')" == 'Monday' ] && echo True [[ $(date +%A|tr -d '\n') == 'Monday' ]] && echo True [[ $(date +%A|tr -d '\n') == "Monday" ]] && echo True

In the end following is working: [[ $(date +%A|tr -d '\n') == $(echo -n "Montag") ]] && echo True

Can someone explain this behavior of bash to me? The used bash is version 4.4.19.

best regards, akendo

Upvotes: 1

Views: 54

Answers (1)

match
match

Reputation: 11060

You are using the English word Monday in your attempts, but your working example uses Montag. I'm going to guess you're using a DE locale.

You can fix this by either using Montag in your comparison, or if you really need to use English words, do something like:

LC_ALL=en_US.utf8 date +%A

To force using an English locale.

Upvotes: 1

Related Questions