首页 > 解决方案 > Bash 脚本无法从变量中正确读取路径

问题描述

很抱歉造成混淆,感谢 kvantour 指出我正在阅读,$errors_path但也将文件保存到$errors_path,我忽略了这一点。从那时起,我已经改变$errors_path了一段时间,$errors并且脚本像它应该的那样工作。我也更改了下面的代码。

我在这里尝试做的是读取日志文件的路径并将它们添加到变量中,然后读取日志中可能发生的错误并将它们也添加到变量中。然后我读取第一个日志文件并搜索今天的日期,如果找到匹配项,则将其添加到 temp.txt。然后我从 temp.txt 中读取第一行和第一个错误行,然后搜索确切的错误,如果找到匹配项,它将日志行添加到名为 logs.log 的文件中。重复相同的过程,直到已读取所有日志文件。

这是完整的代码:


#!/bin/bash

#Get the names of the files that contain the logs
log_files_path="$HOME/logs_path.txt"

#Get the file that contains the errors
errors_path="$HOME/errors_path.txt"

#Get today's date
today_date="$( date +%Y' '%b' '%d )"

#Read the log files location
while read -r log_path
do

    if [ "${log_path}" == "" ]
    then
        echo "${log_path}" > /dev/null
    else
        #Get todays date, search in the log files and add every match to temp.txt
        awk -v dates="${today_date}" '$0 ~ dates' "${log_path}" > "$HOME/temp.txt"
        logs1="$HOME/temp.txt"

        #Read the first line of temp.txt
        while read -r log
        do

            if [ "${log}" == "" ]
            then
                echo "${log}" > /dev/null
            else
                #Read the error
                while read -r errors
                do

                    if [ "${errors}" == "" ]
                    then
                        echo > /dev/null
                    else
                        #If error matches first line add the line to logs.log file
                        if [ "$( echo "${log}" | grep -iE "${errors}" )" ]
                        then
                            echo "${log}" >> "$HOME/logs.log"
                        fi
                    fi

                done < "${errors_path}"
            fi
        done < "${logs1}"
    fi
done < "${log_files_path}"

#Remove temp.txt
rm "$HOME/temp.txt"

标签: linuxbashshell

解决方案


推荐阅读