1

I am writing an If then else script to check if a certain value exists in a file. If the value exists, print value exists, else print value does not exist.

#!/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
  • Hey ItGuru1, what is the question? Let us know, then we can help you. – Joe M Sep 24 '18 at 16:52
  • 1
    Paste your code into shellcheck.net for bash syntax errors – glenn jackman Sep 24 '18 at 17:05
  • My script keeps failing at this line: "If [ $Qualyfile|grep $QualysID = $QualysID ]; then ". Not sure what I need to do to fix. All I am trying to do is search a file for a certain number. If that number is there, print some message. If that number is not there, print some other message. Here is the error in debug mode: ------------------------------- ./zero.research: line 14: syntax error near unexpected token then' ./zero.research: line 14: If [ $Qualyfile|grep $QualysID = $QualysID ]; then ' – ITguru1 Sep 24 '18 at 17:14
1

Note that, after if, you put a command. Depending on the exit status of that command, you enter the then block or the else block. Also note that [ is a command, not just syntax (at a bash prompt, type help [ then help test)

You want

#!/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

Since grep uses regular expressions, this may return false positives. For example, if qid=., grep returns "true" if there is at least one character in the file. Read man grep for the extensive options to help narrow your results (hint, consider the -w and -F options.

Note also that I have avoided using ALLCAPS variable names. They can cause problems if you're not careful. Best practice is to avoid using them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.