How to print the entire line in BASH
I am new to bash scripting and I am trying to print out the whole line but could not 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 conclusion:
Audit Criteria: Warning banner exist.
Vulnerability: No.
Details: WARNING:
instead WARNING:Authorized uses only
All activity may be monitored and reported.
, in "Details" only "WARNING" appeared:
I believe that the problem lies in
MOTD=`cat /etc/motd | awk '{print $1}'`
and
if [ "$MOTD" = "WARNING" ]
parts, I tried {print$0}
but still couldn't get it to work.
source to share
I am assuming you want the first line /etc/motd
, not the first word. If so, use the following:
MOTD=$(head -1 /etc/motd)
and then do string comparison with
if [[ $MOTD == WARNING* ]; then
You can check String in bash for more information on checking if a string contains a specific substring in bash.
source to share
It might be easier to do all of this 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 exit
at the end of the block means that only the first line of the file is processed.
The above code is the most similar to your bash script, but you can make it much shorter with 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
source to share
You are only using the MOTD variable and it only has a WARNING value.
#!/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 if you have multiple lines in / etc / motd and you only need to print one line.
#!/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
source to share