Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search log file for string with bash script

Tags:

string

grep

bash

I just started learning PHP. I'm following phpacademy's tutorials which I would recommend to anyone. Anyways, I'm using XAMPP to test out my scripts. I'm trying to write a bash script that will start XAMPP and then open firefox to the localhost page if it finds a specific string, "XAMPP for Linux started.", that has been redirected from the terminal to the file xampp.log. I'm having a problem searching the file. I keep getting a:

grep: for: No such file or directory

I know the file exists, I think my syntax is wrong. This is what I've got so far:

loaded=$false
string="XAMPP for Linux started."

echo "Starting Xampp..."

sudo /opt/lampp/lampp start 2>&1 > ~/Documents/xampp.log

sleep 15

if grep -q $string ~/Documents/xampp.log; then

    $loaded=$true
    echo -e "\nXampp successfully started!"

fi

if [$loaded -eq $true]; then

    echo -e "Opening localhost..."
    firefox "http://localhost/"

else

    echo -e "\nXampp failed to start."
    echo -e "\nHere's what went wrong:\n"
    cat ~/Documents/xampp.log

fi
like image 811
thecakeisalie Avatar asked Feb 23 '23 23:02

thecakeisalie


2 Answers

In shell scripts you shouldn't write $variable, since that will do word expansion on the variable's value. In your case, it results in four words.

Always use quotes around the variables, like this:

grep -e "$string" file...

The -e is necessary when the string might start with a dash, and the quotes around the string keep it as one word.

By the way: when you write shell programs, the first line should be set -eu. This enables *e*rror checking and checks for *u*ndefined variables, which will be useful in your case. For more details, read the Bash manual.

like image 114
Roland Illig Avatar answered Feb 25 '23 11:02

Roland Illig


You are searching for a string you should put wihtin quotes.
Try "$string" instead of $string

like image 26
ztank1013 Avatar answered Feb 25 '23 12:02

ztank1013