For files in a directory, only the file name is echo (no path)

How can I repeat only the file name if I iterate over a directory with a for loop?

for filename in /home/user/* do echo $filename done; 

will pull out the full path with the file name. I just need a file name.

+82
bash shell
Jan 25 '12 at 22:18
source share
4 answers

If you want a native bash solution

 for file in /home/user/*; do echo "${file##*/}" done 

The above uses a parameter extension, which is native to the shell and does not require calling an external binary basename such as basename

However, can I suggest just find

 find /home/user -type f -printf "%f\n" 
+136
Jan 25 '12 at 22:20
source share

Just use basename :

 echo `basename "$filename"` 

Quotation marks are needed if $ filename contains, for example. space.

+40
Jan 25 '12 at 22:20
source share

Use basename :

 echo $(basename /foo/bar/stuff) 
+14
Jan 25 '12 at 22:21
source share

Another approach is to use ls when reading the list of files in a directory to give you what you want, that is, "just the file name / s". In contrast to reading the full path to the file and then retrieving the file name component in the body of the for loop.

An example below that follows your original:

 for filename in $(ls /home/user/) do echo $filename done; 

If you run the script in the same directory as the files, it just becomes:

 for filename in $(ls) do echo $filename done; 
+5
Jul 13 '18 at 5:49
source share



All Articles