2
#!/bin/bash

i=0
d="$(date +%d)"
#wrong one:
#an="$(cal | awk '/[0-9]/ {print $2}' | tail -2)"
# fixed one:
an="$(cal | col -b | sed 's/_//g' | awk '/[0-9]/ {print $2}' | tail -2)"
for e in $an
do
  if [ "$d" -eq "$e" ]; then
    i=1
  fi
done

echo i=$i

The problem is with $an/$e but i don't understand why and how to fix it. I've looked and it don't have any spaces, they are numbers however bash don't think this way.

<< EDIT >>

Ok i agree, maybe i've chosen the wrong way to do it, just thought that with cal it would be simple. Its part of a bigger script so i need to get a result from it so that script could proceed further down the code. I need to get 2 last mondays, tuesadays,..., or sundays and compare it with today, if the sate is the same give this info to the script.

4

2 回答 2

2

cal | less如果您手边没有 ascii 打印机,cal 今天使用 overstrike 来下划线。

您需要先将其过滤掉。

col 是工具

i=0
d="$(date +%d)"
an="$(cal | col -b | awk '/[0-9]/ {print $2}' | tail -2)"
for e in $an
do
  if [ "$d" -eq "$e" ]; then
    i=1
  fi
done

另一种选择是今天是一个月中最后两个星期一之一。

 # must be GNU date
 (( `date -d '2 weeks' +' i = %d < 14 && %w == 1 '` ))

此表达式将 i 设置为 1 或 0 并返回 true 或 false 如果您希望使用“周日错误”13 days %w == 0而不是2 weeks %w == 1

于 2014-12-29T10:01:29.360 回答
1

如果您解释了您要解决的问题,将会有所帮助。以下可能是更好的方式来说明“今天是本月最后两个星期一之一吗?” 我认为这是您的代码试图做的事情。

cal | awk -v d=$(date +%d) '$2==d { x=2 }
    /[0-9]/ { x-- }
    END { exit (!(x >= 0)) }' && i=1

当然有多种方法可以将其分割,但上面将大部分逻辑重构为 Awk —— 因为无论如何你都在使用它,所以要充分利用它。

于 2014-12-29T10:22:20.003 回答