thecakeisalie
thecakeisalie

Reputation: 43

Search log file for string with bash script

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

Upvotes: 4

Views: 9937

Answers (3)

Karoly Horvath
Karoly Horvath

Reputation: 96266

There are a couple of problems:

  • quote variables if you want to pass them as a simple argument "$string"
  • there is no $true and $false
  • bash does variable expansion, it substitutes variable names with their values before executing the command. $loaded=$true should be loaded=true.
  • you need spaces and usually quotes in the if: if [$loaded -eq $true] if [ "$loaded" -eq true ]. in this case the variable is set so it won't cause problems but in general don't rely on that.

Upvotes: 1

ztank1013
ztank1013

Reputation: 7255

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

Upvotes: 1

Roland Illig
Roland Illig

Reputation: 41625

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.

Upvotes: 7

Related Questions