Can't get result from grep in bash loop
Can't get result from grep in bash loop
I'm trying to get info from log files using grep + tail -1:
#!/bin/bash
# declare an array called array and define 3 vales
array=( 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 )
array2=( 00 30 )
for i in "${array[@]}"
do
for j in "${array2[@]}"
do
output=$(grep filtered /home/pavel/hasoffers_api/logs/tabatoo2_20180627$i$j* | tail -1)
echo /home/pavel/hasoffers_api/logs/tabatoo2_20180627$i$j*
echo "$output"
done
done
this outputs just empty string, but I definitely know that phrase "filtered" is in the logs.
What can be the problem?
I tried several variations of the same script but it just returns empty string.
Thanks!
Also see How to use Shellcheck, How to debug a bash script? (U&L.SE), How to debug a bash script? (SO), How to debug bash script? (AskU), Debugging Bash scripts, etc.
– jww
Jun 29 at 10:21
Thank you for comments, the script is actually working well, the phrase was different, my bad. Thanks!
– paus
Jun 29 at 10:32
2 Answers
2
In this kind of assignment of a output value you should always redirect standard error (stderr) to standard out put (stdout). In your case if grep filtered /home/pavel/hasoffers_api/logs/tabatoo2_20180627$i$j*
fails the error output will not be stored in variable output
hence it will be difficult for you to debug the program. Change your script like below where error message will also be assigned to variable output
.
grep filtered /home/pavel/hasoffers_api/logs/tabatoo2_20180627$i$j*
output
output
output=$(grep filtered /home/pavel/hasoffers_api/logs/tabatoo2_20180627$i$j* 2>&1 | tail -1)
Now if search string is not available echo $output
will print a empty string and if log file is not available it will print the error message
echo $output
Hope this will help you.
For start maybe try to test if the file you get by building string "tabatoo2_20180627$i$j*" even exists.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
I think the script looks ok. The only explanation I see is that the string "filtered" is not in the logs or there's no files named ".../tabatoo2_201806270000*". Without log files I/we can't reproduce the problem.
– Kamil Cuk
Jun 29 at 8:42