【问题标题】:Bash script is working only in path where is bash script fileBash 脚本仅在 bash 脚本文件所在的路径中工作
【发布时间】:2018-10-11 09:42:35
【问题描述】:

我想获取目录中的最后一个(最新)文件。这个脚本适用于我有 bash 文件的目录。 当我将路径更改为另一个路径时,问题在last_modified。脚本看不到file - 我想,但我不知道为什么。有人可以帮忙吗?

下面是我的 test.sh 文件中的代码

#!/bin/bash

file=$(cd '/path_where_is_test.sh_file' && ls -t | head -1)
last_modified=$(stat -c %Y $file)
current=$(date +%s)

if (( ($current - $last_modified) > 86400 )); then
    echo 'Mail'
else
    echo 'No Mail'
fi;

【问题讨论】:

  • 您正在更改目录,但是当调用 Stat 时,您又回到了原始目录。因此,您还必须添加 stat 的路径。

标签: linux bash ubuntu filter last-modified


【解决方案1】:

问题是您在cd 之后使用ls 到特定目录。 ls 的输出只是一个没有路径的文件名。稍后您将该文件名不带路径传递给stat 命令。如果您的当前目录不同,则stat 将找不到该文件。

可能的解决方案:

  • 将目录 (dir) 添加到 stat 命令中

    dir='/path_where_is_test.sh_file'
    file=$(cd "$dir" && ls -t | head -1)
    last_modified=$(stat -c %Y "$dir/$file")
    
  • 使用更改后的目录

    last_modified=$(cd '/path_where_is_test.sh_file' && stat -c %Y $(ls -t | head -1))
    

【讨论】:

  • 非常感谢您的帮助 :)
猜你喜欢
  • 2016-12-27
  • 2021-05-31
  • 2011-02-05
  • 2023-03-07
  • 2010-11-11
  • 2013-03-23
  • 2021-08-28
  • 2017-12-07
相关资源
最近更新 更多