faj*_*ide 2 bash shell if-statement
这是我的第一个bash脚本,为了获取每小时数据减少的数据,我创建了一个已经运行的bash脚本,但我认为使用"if ... else"语句太长了,可能有循环,而直到?
#!/bin/bash
x=$(date +"%H")
y=$(sed -n "/END_TIME/=" file.txt)
if [ $x = 00 ]; then
s=$(($y-24))
echo "this time 00:00"
elif [ $x = 23 ]; then
s=$(($y-1))
echo "this time 23:00"
elif [ $x = 22 ]; then
s=$(($y-2))
echo "this time 22:00"
elif [ $x = 21 ]; then
s=$(($y-3))
echo "this time 21:00"
elif [ $x = 20 ]; then
s=$(($y-4))
echo "this time 20:00"
.
.
.
elif [ $x = 01 ]; then
s=$(($y-23))
echo "this time 01:00"
else
echo "this time not data"
fi
z=$(awk 'NR=='$s' {print $0}' file.txt)
#print
echo "Time : " $x
echo "Line End_time : " $y
echo "Show Line Data : " $z
Run Code Online (Sandbox Code Playgroud)
此示例数据file.txt:
0 3419973
1 2302205
2 1535190
3 1045063
4 895020
5 1275980
.
.
.
.
21 6953924
22 6423911
23 5075690
END_TIME
Run Code Online (Sandbox Code Playgroud)
如果我想在21:00获取"file.txt"中的数据,那么它将打印:
Time : 21:00
Line END_time : 24
Show Line Data : 21 6953924 *(I was looking for this)*
Run Code Online (Sandbox Code Playgroud)
这与cron一起运行.如果可以帮助我?
我认为你可以将案件减少到:
case $x in
24)
s = $(($y-1))
echo "this time 00:00"
;;
23 | 22 | ... | 01) # or [01][0-9] | 2[0-3])
s = $(($y - 25 + $x))
echo "this time $x:00"
;;
*)
echo "this time not data"
;;
esac
Run Code Online (Sandbox Code Playgroud)