bc81
bc81

Reputation: 187

bash if statement remove redundant lines

Is there a way to write the below without having to copy and paste the command multiple times?

success - it will print the "grep" to console and to the log file

failure - it will print the " console and to the log file as well

  if wget -S --spider ${proxystring}"$1" 2>&1 | grep 'HTTP/1.1 200 OK'; then
     wget -S --spider ${proxystring}"$1" 2>&1 | grep 'HTTP/1.1 200 OK' >> $LOGFILE
     return 0;
  else
      wget -S --spider ${proxystring}"$1" 2>&1 | $TEELOG
     return 1;
  fi

Upvotes: 0

Views: 54

Answers (3)

chepner
chepner

Reputation: 530970

There's a special case you could take advantage of, I think. If you use grep -v 'HTTP/1.1 200 OK', you obviously get no output if the match fails, but you get exactly HTTP/1.1 200 OK if it succeeds (there's no other text on such a status line).

As such, you can unconditionally write the output of grep to $TEELOG, but hard-code the 200 response to LOGFILE when grep fails.

if ! wget -S --spider "$proxystring$1" 2>&1 | grep -v 'HTTP/1.1 200 OK' | $TEELOG; then
  return 1
else
  echo 'HTTP/1.1 200 OK' >> "$LOGFILE"
  return 0
fi

(By the way, I suspect TEELOG is something like tee somefile; use a shell function instead of a variable:

TEELOG () {
  tee somefile
}

)

Upvotes: 0

Jack
Jack

Reputation: 6158

You only have to run the wget once. Store the results in a temp file and work with that:

# Make temporary file
tmpfile=$(mktemp)

# put wget output in temp file
wget -S --spider "${proxystring}$1" 2>&1 > "$tmpfile"

# grep in temp file
grep_result=$( grep 'HTTP/1.1 200 OK' "$tmpfile" )

# If string found...
if [ $? -eq 0 ]; then
    # Append grep results to log file
    echo "$grep_result" >> $LOGFILE

    # remove temp file
    rm "$tmpfile"

    # Success!!
    return 0;

# otherwise...
else
    # put the wget results in TEELOG
    cat "$tmpfile" >> "$TEELOG"

    # remove temp file
    rm "$tmpfile"

    # Fail :(
    return 1;

fi

Upvotes: 2

RaphaMex
RaphaMex

Reputation: 2839

Store the output in a variable then use this variable as many time as you want:

ret_value=`wget -S --spider ${proxystring}"$1" 2>&1 | grep 'HTTP/1.1 200 OK';`
if [ $? -eq 0 ]; then
    echo $ret_value >> $LOGFILE
    return 0;
else
    wget -S --spider ${proxystring}"$1" 2>&1 | $TEELOG
    return 1;
fi

Upvotes: 0

Related Questions