[英]Bash script is working only in path where is bash script file
我想獲取目錄中的最后一個(最新)文件。 這個腳本適用於我擁有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;
問題是您在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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.