I'm trying to list specific files in a different dir rather than the current dir.
Look at this simple log:
[johni /share/ex_data/ex4] > ls
example.c header1.h header3.h
example2.c header2.h
[johni /share/ex_data/ex4] > ls -t header*
header1.h header2.h header3.h
[johni /share/ex_data/ex4] > cd
[johni ~] >
[johni ~] >
[johni ~] > ls -t header* /share/ex_
ex_data/ ex_sol/
[johni ~] > ls -t header* /share/ex_data/ex4
ls: No match
How could I use that 'ls' command from another dir on that same /share/ex_data/ex4 dir?
Thanks !!.
If you're expecting output including the qualified directory name, then you can simply use
ls -t /share/ex_data/ex4/header*
If you don't want the directory names to be included, use a subshell that changes directory before invoking ls
(as a performance enhancement, this uses exec
to generate only one new process table entry rather than potentially requiring two):
(cd /share/ex_data/ex4 && exec ls -t header*)
That said, if this is being done for a script -- say, to find the newest or oldest filename - it's bad practice to parse ls
; other techniques are available to find the newest or oldest file (and you should follow the latter link above if this is all you want to do, rather than using the more complicated code given below to provide a full ordering).
For instance, if you have GNU find
, GNU sort
and bash and wanted to load a list of files into an array by mtime
, the following will work with filenames which will completely throw off ls -t
-- including names containing newlines and the like:
filenames_by_mtime=( )
while read -r -d ' ' time && IFS= read -r -d '' filename; do
filenames_by_mtime+=( "$filename" )
done < <(find /share/ex_data/ex4 \
-maxdepth 1 \
-type f \
-name 'header*' \
-printf '%T@ %P\0' \
| sort -z -n)
...this array can then be expanded with "${filenames_by_mtime[@]}"
, or indexed into for an individual entry -- for instance, the oldest file would be "${filenames_by_mtime[0]}"
.