如何在BASH中打印整行

时间:2014-11-13 11:45:17

标签: linux bash if-statement awk

我是bash脚本新手,我一直试图打印出整条生产线但却无法找到工作方式。

这是我的代码

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

我的输出是:

Audit Criteria: Warning banner exist.
Vulnerability: No.
Details: WARNING:

而不是WARNING:Authorized uses only All activity may be monitored and reported.,只有"警告"出现在细节中:

我认为问题出在

MOTD=`cat /etc/motd | awk '{print $1}'` 

if [ "$MOTD" = "WARNING" ]部分,我已经尝试了{print$0},但仍无法让它发挥作用。

3 个答案:

答案 0 :(得分:2)

我想你想获得/etc/motd的第一行,而不是第一个单词。如果是这样,请使用以下内容:

MOTD=$(head -1 /etc/motd)

然后用

进行字符串比较
if [[ $MOTD == WARNING* ]; then

您可以查看String contains in bash以获取有关检查字符串是否包含bash中特定子字符串的更多信息。

答案 1 :(得分:2)

也许在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

条件末尾的条件NR==1exit表示只处理文件的第一行。

上面的代码与你的bash脚本最相似,但你可以使用变量缩短它:

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

答案 2 :(得分:0)

您仅使用变量MOTD并且它仅具有值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

或者,如果/ etc / motd中有多行,则需要只打印一行。

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