Reputation: 75
I am trying to run a for loop as below without success
hour=`date +%H -d "1 Hour Ago"`
cd /Log1/
for i in `seq -w 00 "$hour"`; // $hour not working
do
zgrep -a "Packet" LOG1.txt| grep "#SUCCESS#" |wc -l >>success_chour.txt
zgrep -a "Packet" LOG2.txt| grep "#FAIL#" |wc -l >>fail_chour.txt
done
I have tried $hour
, "$hour"
, and '$hour'
without success.
Upvotes: 0
Views: 171
Reputation: 295443
It's not clear what "without success" means in this context, since you're not even trying to expand $i
anywhere inside the body of your loop.
That said, using seq
is actually not ideal -- it's a nonstandard tool not built into bash. Better to use functionality guaranteed to be available everywhere the shell is:
# Calculate both day and hour at once
log_scan_end_time=$(date -d "1 hour ago" '+%Y-%M-%d-%H')
# ...then create log_scan_prefix by removing the hour
log_scan_prefix=${log_scan_end_time%-*}
# and extract the hour alone
max_hour=${log_scan_end_time##*-}
for ((cur_hour=0; cur_hour<max_hour; cur_hour++)); do
printf -v cur_hour_str '%02d' "$cur_hour" # generate a 0-padded string
logs=( Packet*"${log_scan_prefix}-${cur_hour_str}"*.gz )
[[ -e ${logs[0]} ]] || {
echo "No logs found matching pattern ${logs[0]}" >&2
continue
}
# print a header line in the output file to allow diagnosing results
for f in success_chour.txt fail_chour.txt; do
{
printf '# '
printf '%q ' "${logs[@]}"
printf '\n'
} >>"$f"
done
zgrep -E -a --count \
-e '(Packet.*#SUCCESS#)|(#SUCCESS#.*Packet)' \
-- /dev/null "${logs[@]}" >>success_chour.txt
zgrep -E -a --count \
-e '(Packet.*#FAIL#)|(#FAIL#.*Packet)' \
-- /dev/null "${logs[@]}" >>fail_chour.txt
done
Upvotes: 0
Reputation: 56
jiapingzjp@jiapingzjp-Dell:~$ cat my.sh
hour=`date +%H -d "1 Hour Ago"`
for i in `seq -w 00 "$hour"`;
do
echo $i
done
jiapingzjp@jiapingzjp-Dell:~$ bash my.sh
00 01 02 03 04 05 06 07 08 09 10 11 12
I think the code is OK, I try both "bash test.sh"
"dash test.sh"
in ubuntu system, it works fine. Maybe you can show what the error message you get and what the command you run.
Upvotes: 2