Reputation: 501
I'm new to bash scripting and I've been trying to print out the entire line but couldn't find a way to work.
This is my code
#!/bin/bash
MOTD=`cat /etc/motd | awk '{print $1}'`
if [ "$MOTD" = "WARNING" ]
then
echo "Audit Criteria: Warning banner exist."
echo "Vulnerability: No."
echo "Details: $MOTD "
else
echo "Audit Criteria: Warning banners does not exist."
echo "Vulnerability: Yes."
echo "Details: $MOTD "
fi
my output is:
Audit Criteria: Warning banner exist.
Vulnerability: No.
Details: WARNING:
instead of the WARNING:Authorized uses only
All activity may be monitored and reported.
, only "WARNING" appeared in the Details:
I believe the problem lies on the
MOTD=`cat /etc/motd | awk '{print $1}'`
and
if [ "$MOTD" = "WARNING" ]
parts, I've tried {print$0}
but still could not get it to work.
Upvotes: 3
Views: 979
Reputation: 74595
Perhaps it would be simpler to do the whole thing in awk:
awk 'NR==1{
if($1=="WARNING") {
print "Audit Criteria: Warning banner exists."
print "Vulnerability: No."
}
else {
print "Audit Criteria: Warning banner does not exist."
print "Vulnerability: Yes."
}
print "Details: " $0
exit
}' /etc/motd
The condition NR==1
and the exit
at the end of the block mean that only the first line of the file is processed.
The code above is the most similar to your bash script but you could make it a lot shorter using variables:
awk 'NR==1{if($1=="WARNING"){b="exists";v="No"}else{b="does not exist";v="Yes"}
printf "Audit Criteria: Warning banner %s.\nVulnerability: %s.\nDetails: %s\n",b,v,$0
exit}' /etc/motd
Upvotes: 2
Reputation: 1823
You are using only using variable MOTD and it is having only value WARNING.
#!/bin/bash
MOTD=`cat /etc/motd | awk '{print $1}'`
if [ "$MOTD" = "WARNING" ]
then
echo "Audit Criteria: Warning banner exist."
echo "Vulnerability: No."
echo "Details: `cat /etc/motd` "
else
echo "Audit Criteria: Warning banners does not exist."
echo "Vulnerability: Yes."
echo "Details: `cat /etc/motd`"
fi
Or in case if you have multiple lines in /etc/motd and you need to print only one line then.
#!/bin/bash
MOTDL=`grep WARNING /etc/motd`
MOTD=`cat /etc/motd | awk '{print $1}'`
if [ "$MOTD" = "WARNING" ]
then
echo "Audit Criteria: Warning banner exist."
echo "Vulnerability: No."
echo "Details: $MOTDL "
else
echo "Audit Criteria: Warning banners does not exist."
echo "Vulnerability: Yes."
echo "Details: $MOTDL"
fi
Upvotes: 0
Reputation: 289555
I guess you want to get the first line of /etc/motd
, not the first word. If so, use the following:
MOTD=$(head -1 /etc/motd)
and then do the string comparison with
if [[ $MOTD == WARNING* ]; then
You can check String contains in bash for more information about check if a string contains a specific substring in bash.
Upvotes: 2