Manish Tiwari
Manish Tiwari

Reputation: 17

until loop for bash scripting

I want to use Until loop command in the following way, Using until loop so that script should not end if condition is false

#!/bin/bash
read -p " enter the App name : " app
file="/logs/$app/$app.log"
if ! [ -f "$file" ]; then
    echo "$app.log not found, Please check correct log name in deployer"
    exit
fi

format=$(head -1 $file | awk '{print $1,$2,$3}')
format1=$(tail -1 $file | awk '{print $1,$2,$3}')
read -p " Enter the Date in this Format --'$format' : " first
until grep -q "$first" "$file"
do
  echo "Date not found"
  read -p " Enter the Date in this Format --'$format' : " first
done
final_first=$first
echo "logs are present till this '$format1' date, use this date if you want logs from Provided to latest."
read -p "Enter the end date : " end
until grep -q "$end" "$file"
do
  echo "Date not found"
  read -p "Enter the end date : " end
done
final_end=$end
cd /logs/$app
sed -n " /$final_first/,/$final_end/ "p $file >$app.txt
zip $app.zip $app.txt
rm $app.txt

but I am getting this input

$ ./test
 enter the App name : cspt
 Enter the Date in this Format --'Sep 08 04:53:30' : er
logs are present till this 'at java.lang.Thread.run(Thread.java:662) ' date, use this date if you want logs from Provided to latest.
Enter the end date : Sep 08 04:53:30
  adding: cspt.txt (deflated 99%)

Here it not taking end date.. and generating log file

Upvotes: 0

Views: 240

Answers (1)

John Bollinger
John Bollinger

Reputation: 180528

but I am getting this input

$ ./test
 enter the App name : cspt
 Enter the Date in this Format --'Sep 08 04:53:30' : er
logs are present till this 'at java.lang.Thread.run(Thread.java:662) ' date, use this date if you want logs from Provided to latest.
Enter the end date : Sep 08 04:53:30
  adding: cspt.txt (deflated 99%)

Here it not taking end date.. and generating log file

On the contrary, it looks like it indeed is prompting for and reading an end date (given as Sep 08 04:53:30 in the example). Do you perhaps mean to say that you expect the script to reject er as a start date?

Perhaps the script could be made more discriminating, but I see no reason to think it's doing anything different from what you told it to do. You accept as a start "date" any string that appears anywhere in the file, more or less. It is not unreasonable to think that the string "er" would appear somewhere in a lengthy log file.

Note also, however, that your script may behave unexpectedly if either of the given "dates" contains regex metacharacters. Such dates may be matched where you don't expect.

Furthermore, dates containing slash (/) characters will cause problems for your sed command.

Upvotes: 1

Related Questions