Getting file name ?

Assuming /dir1/dir2 has two file

file1
file2

If I get the file name which includes the dir name using command

file_name=`ls -ltr /dir1/dir2/* | grep '^-' | tail -1 | awk '{print $9}' `

then I get file_name which includes the /dir1/dir2 also.

if I want to get just the filename which should be file1 or file2 then how can I do that?

file_name=`ls -ltr /dir1/dir2 | grep '^-' | tail -1 | awk '{print $9}' `

to avoid the directory path in your variable

I wouldn't use four external commands just the get a filename. However, once you have it, it's a simple matter of parameter expansion:

file_name=${file_name##*/}

This Worked.

file_name=`ls -ltr /dir1/dir2 | grep '^-' | tail -1 | awk '{print $9}' `

>>
I wouldn't use four external commands just the get a filename
>>

Is there an alternate to just get the latest file name from a dir?

I used grep to just get files from a dir or skip the dirs underneath it, tail -1 gives the latest file name. Awk just prints the name.

Thanks.

:b:

As a simple example of how you could simply it, you could get rid of the grep and tail.

dir=/dir1/dir2  ## adjust to taste
file_name=$(
 ls -t "$dir" |
 while IFS= read -r file
 do
   [ -f "$dir/$file" ] && { printf "%s\n" "$file"; break; }
 done
)