if [ "date_str" == "latest_time" ]; then
时间: 2023-07-21 16:33:47 浏览: 34
这个if语句的判断条件不正确,因为它比较的是字符串"date_str"和"latest_time",而不是变量$latest_time和$date_str的值。这可能是因为if语句中date_str和latest_time被放在了双引号中,导致它们被当作字符串常量而不是变量。正确的写法应该是:
```
if [ "$date_str" == "$latest_time" ]; then
```
这样if语句就可以正确比较$date_str和$latest_time的值了。
相关问题
if [ $(find /var/log/program_monitor/ -maxdepth 1 -name "*.log" | wc -l) -gt 0 ]; then echo "1" latest_log=$(ls -t /var/log/program_monitor/*.log | head -1) echo "2" echo "$latest_log" date_str=$(echo $latest_log | cut -d'/' -f5 | grep -oE '[0-9]{8}') echo "3" echo "$date_str" latest_time=$(date +%Y%m%d) echo "4" echo "$latest_time" if [ "date_str" == "latest_time" ]; then echo "5" echo ---------$(date)---------- >> $log_file else touch ${log_file} fi else touch ${log_file} echo "6" fi为啥date_str=$(echo $latest_log | cut -d'/' -f5 | grep -oE '[0-9]{8}')这个获取的数据不会更新一直是一个值
这段代码是在查找指定目录下最新的日志文件,并判断它的日期是否与当前日期相同,如果不同则向日志文件写入新的时间戳。而date_str=$(echo $latest_log | cut -d'/' -f5 | grep -oE '[0-9]{8}')是用来提取日志文件名中的日期部分的,其中cut -d'/' -f5是用来取出文件名,grep -oE '[0-9]{8}'是用来提取8位数字的部分作为日期。
如果date_str的值一直不更新,那么可能是因为最新的日志文件名中的日期部分没有发生变化,所以提取出来的日期值也没有变化。你可以检查一下最新的日志文件名是否确实有日期部分,以及它是否随着时间的推移而变化。
function monitor(){ #set -x #if [ -e `/var/log/program_monitor/*.log` ];then if [ $(find /var/log/program_monitor/ -maxdepth 1 -name "*.log" | wc -l) -gt 0 ]; then echo "1" latest_log=$(ls -t /var/log/program_monitor/*.log | head -1) echo "2" date_str=$(echo $latest_log | cut -d'/' -f5 | grep -oE '[0-9]{8}') echo "3" echo "$date_str" latest_time=$(date +%Y%m%d) echo "4" echo "$latest_time" if [ "date_str" == "latest_time" ]; then echo "5" echo ---------$(date)---------- >> $log_file else touch ${log_file} fi else touch ${log_file} echo "6" fi }为啥不打印5明明获得的字符串都是一样的
根据代码分析,问题可能出在判断语句中。在判断语句中,字符串 "date_str" 和 "latest_time" 被引号包含,被视为文本字符串,而不是变量。所以无论实际的值是什么,它们都是不相等的文本字符串。正确的写法应该是去掉引号,将变量的值直接作为字符串比较,即:
```if [ "$date_str" == "$latest_time" ]; then```