I need to compare two dates which are stored in two variables, the format is YYYY-MM-DD . I suppose I can store them in another variables and use some tr -d "-",then compare like integers, but I don’t know how. Thanks in advance !
- why not string operation ?resultsway– resultsway2015-03-27 22:12:47 +00:00Commented Mar 27, 2015 at 22:12
- I tried [ var1 > var2 ] but it turns true every timenocturne– nocturne2015-03-27 22:17:20 +00:00Commented Mar 27, 2015 at 22:17
Add a comment |
2 Answers
You may need to call out to expr, depending on your mystery shell:
d1="2015-03-31" d2="2015-04-01" if [ "$d1" = "$d2" ]; then echo "same day" elif expr "$d1" "<" "$d2" >/dev/null; then echo "d1 is earlier than d2" else echo "d1 is later than d2" fi d1 is earlier than d2 The test command (or it's alias [) only implements string equality and inequality operators. When you give the (non-bash) shell this command:
[ "$d1" > "$d2" ] the > "$d2" part is treated as stdout redirection. A zero-length file named (in this case) "2015-04-01" is created, and the conditional command becomes
[ "$d1" ] and as the variable is non-empty, that evaluates to a success status.
The file is zero size because the [ command generates no standard output.