我正在编写 If then else 来检查文件中的特定数值

我正在编写 If then else 来检查文件中的特定数值

我正在编写一个 If then else 脚本来检查文件中是否存在某个值。如果值存在,则打印值存在,否则打印值不存在。

#!/bin/bash
#This script will check a file and determine if the QID exists.
#search the zero day file for qids and system tracking id's. These are contained in
#the file file.

echo What is the QID number $HOME?
read QID

#Set some variables
Qualyfile=$(cat /home/dc368/zeroday/zerodayresearch)
QualysID=$QID

If [ $Qualyfile|grep $QualysID = $QualysID ]; then 
    echo qid exists
else echo qid does not exist
fi

答案1

请注意,在 后if,您放置了命令。取决于退出状态使用该命令,您可以输入一个then或多个else块。另请注意,这[是一个命令,不仅仅是语法(在 bash 提示符下,输入help [then help test

你要

#!/bin/bash
read -p "What is the QID? " qid
file=/home/dc368/zeroday/zerodayresearch
if grep -q "$qid" "$file"; then
    echo qid exists
else 
    echo qid does not exist
fi

由于 grep 使用正则表达式,因此可能会返回误报。例如,qid=.如果文件中至少有一个字符,则 grep 返回“true”。阅读man grep广泛的选项来帮助缩小结果范围(提示,考虑-w-F选项。

另请注意,我避免使用全部大写的变量名称。它们可能会引起问题如果你不小心的话。最佳做法是避免使用它们。

相关内容