我正在尝试在bash shell脚本中将grep用作变量和函数。当grep用作变量时,我得到所需的输出。将grep用作函数时,我没有得到想要的输出。
将grep用作变量的脚本如下:
#! /bin/bash
grep=$(grep -ico "mmshutdown: Finished" mmshutdown-output.txt)
#grep()
#{
# grep -ico "mmshutdown: Finished" mmshutdown-output.txt
#}
status()
{
echo $?
}
if [[ "grep" -gt "0" ]];
then
echo
echo "exit code of search mmshutdown: Finished is $(status)"
echo
echo "FILE SYSTEM UNMOUNTED SUCESSFULLY"
sleep 3
else
echo "exit code of search mmshutdown: Finished is $(status)"
echo "check output log file mmshutdown.txt"
sleep 3
fi
运行脚本时的输出是
[root@ad ~]# ./grep-variable.sh
exit code of search mmshutdown: Finished is 0
FILE SYSTEM UNMOUNTED SUCESSFULLY
函数中用于grep的脚本如下:
#! /bin/bash
#grep=$(grep -ico "mmshutdown: Finished" mmshutdown-output.txt)
grep()
{
grep -ico "mmshutdown: Finished" mmshutdown-output.txt
}
status()
{
echo $?
}
if [[ "grep" -gt "0" ]];
then
echo
echo "exit code of search mmshutdown: Finished is $(status)"
echo
echo "FILE SYSTEM UNMOUNTED SUCESSFULLY"
sleep 3
else
echo "exit code of search mmshutdown: Finished is $(status)"
echo "check output log file mmshutdown.txt"
sleep 3
fi
运行脚本时的输出是
[root@ad ~]# ./grep-function.sh
exit code of search mmshutdown: Finished is 1
check output log file mmshutdown.txt
有人可以指出这里出了什么问题吗?为什么将grep用作函数不能提供所需的输出?
答案 0 :(得分:1)
您的两个程序都将“ grep”与“ 0”进行比较,而不是grep命令的输出。 另外-c选项返回匹配的行数。
检查以下与grep一起使用的代码。但是由于grep是一个函数,您将需要调用原始grep即具有完整路径的命令,否则它将陷入无限循环。 将输出发送到/ dev / null并处理命令执行状态。
#! /bin/bash
set -x
#grep=$(grep -ico "mmshutdown: Finished" mmshutdown-output.txt)
grep()
{
return $(/bin/grep -ico "mmshutdown: Finished" mmshutdown-output.txt > /dev/null)
}
status()
{
echo $?
}
if grep;
then
echo
echo "exit code of search mmshutdown: Finished is $(status)"
echo
echo "FILE SYSTEM UNMOUNTED SUCESSFULLY"
sleep 3
else
echo "exit code of search mmshutdown: Finished is $(status)"
echo "check output log file mmshutdown.txt"
sleep 3
fi