Search code examples
bashshell

For files in directory, only echo filename (no path)


How do I go about echoing only the filename of a file if I iterate a directory with a for loop?

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

will pull the full path with the file name. I just want the file name.


Solution

  • If you want a native bash solution

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

    The above uses Parameter Expansion which is native to the shell and does not require a call to an external binary such as basename

    However, might I suggest just using find

    find /home/user -type f -printf "%f\n"