How would I modify this code to give me the full file path of the last modified file in the code directory, including nested sub-directories?
# Gets the last modified file in the code directory.
get_filename(){
cd "$code_directory" || no_code_directory_error # Stop script if directory doesn't exist.
last_modified=$(ls -t | head -n1)
echo "$last_modified"
}
CodePudding user response:
- Use
findinstead ofls, because the use oflsis an anti-pattern. - Use a Schwartzian transform to prefix your data with a sort key.
- Sort the data.
- Take what you need.
- Remove the sort key.
- Post process the data.
find "$code_directory" -type f -printf '%T@ %p\n' |
sort -rn |
head -1 |
sed 's/^[0-9.]\ //' |
xargs readlink -f
CodePudding user response:
You can use the realpath utility.
# Gets the last modified file in the code directory.
get_filename(){
cd "$code_directory" || no_code_directory_error # Stop script if directory doesn't exist.
last_modified=$(ls -t | head -1)
echo "$last_modified"
realpath "$last_modified"
}
Output:
blah.txt
/full/path/to/blah.txt
CodePudding user response:
ls -t sort by modification time and if you want first one you can add | head -1, R helps you recursively sort files, I think the only tips here is ls -tR doesn't stack all files then sort them, so you can use
find . -type f -printf "%T@ %f\n" | sort -rn > out.txt
