Search code examples
linuxbashubuntufilterlast-modified

Bash script is working only in path where is bash script file


I want to get last one (newest) file in the directory. And this script is working for the directory where I have bash file. When I changed the path to another path problem is in last_modified. Script can't see file - I think but I don't know why. Can anybody help?

Below is code in my test.sh file

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

Solution

  • The problem is that you are using ls after cd to a particular directory. The output of ls is just a file name without a path. Later you pass that file name without path to the stat command. If your current directory is different, then stat won't find the file.

    Possible solutions:

    • Add the directory (dir) to the stat command

      dir='/path_where_is_test.sh_file'
      file=$(cd "$dir" && ls -t | head -1)
      last_modified=$(stat -c %Y "$dir/$file")
      
    • Use the changed directory

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