Search log file for string with bash script

I just started learning PHP. I follow the phpacademy instructions that I recommend to everyone. Anyway, I use XAMPP to test my scripts. I am trying to write a bash script that will run XAMPP, and then open firefox on the localhost page if it finds the specific line "XAMPP for Linux is running." This was redirected from the terminal to the xampp.log file. I have a problem finding a file. I keep getting:

grep: for: No such file or directory 

I know the file exists, I think my syntax is incorrect. This is what I have 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 what went wrong:\n" cat ~/Documents/xampp.log fi 
+4
source share
3 answers

In shell scripts, you should not write $variable , since this will do the extension of the word by the value of the variable. In your case, this leads to four words.

Always use quotation marks around variables, for example:

 grep -e "$string" file... 

-e needed when a line can begin with a dash, and the quotation marks around the line save it as a single word.

By the way: when writing shell programs, the first line should be set -eu . This allows * e * rror to check and check for * u * ndefined variables that will be useful in your case. Read more in the Bash manual.

+4
source

You are looking for a string that you must put in wihtin quotation marks.
Try "$string" instead of $string

+1
source

There are several problems:

  • quote variables if you want to pass them as a simple argument "$string"
  • no $true and $false
  • bash performs variable expansion, it replaces the variable names with its values ​​before executing the command. $loaded=$true must be loaded=true.
  • you need spaces and are usually quoted in if: if [$loaded -eq $true] if [ "$loaded" -eq true ] . in this case, the variable is set so that it does not cause problems, but generally does not rely on it.
+1
source

All Articles