[英]Search log file for string with bash script
I just started learning PHP. 我刚开始学习PHP。 I'm following phpacademy's tutorials which I would recommend to anyone.
我正在关注phpacademy的教程,我会推荐给任何人。 Anyways, I'm using XAMPP to test out my scripts.
无论如何,我正在使用XAMPP来测试我的脚本。 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.
我正在尝试编写一个bash脚本,它将启动XAMPP然后将firefox打开到localhost页面,如果它找到一个特定的字符串,“XAMPP for Linux started。”,它已经从终端重定向到文件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
In shell scripts you shouldn't write $variable
, since that will do word expansion on the variable's value. 在shell脚本中,您不应该编写
$variable
,因为这将对变量的值进行单词扩展 。 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. 当字符串可能以短划线开头时,
-e
是必需的,字符串周围的引号将其保留为一个单词。
By the way: when you write shell programs, the first line should be set -eu
. 顺便说一下:当你编写shell程序时,第一行应该
set -eu
。 This enables * e *rror checking and checks for * u *ndefined variables, which will be useful in your case. 这使* e * rror检查并检查* u * ndefined变量,这对您的情况很有用。 For more details, read the Bash manual.
有关更多详细信息,请阅读Bash手册。
You are searching for a string you should put wihtin quotes. 您正在搜索一个字符串,您应该使用引号。
Try "$string"
instead of $string
尝试
"$string"
而不是$string
There are a couple of problems: 有几个问题:
"$string"
"$string"
传递,则引用变量 $true
and $false
$true
和$false
$loaded=$true
should be loaded=true.
$loaded=$true
应该loaded=true.
if [$loaded -eq $true]
if [ "$loaded" -eq true ]
. 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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.