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

BashShell

Bash Problem Overview


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.

Bash Solutions


Solution 1 - Bash

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"

Solution 2 - Bash

Just use basename:

echo `basename "$filename"`

The quotes are needed in case $filename contains e.g. spaces.

Solution 3 - Bash

Use basename:

echo $(basename /foo/bar/stuff)

Solution 4 - Bash

Another approach is to use ls when reading the file list within a directory so as to give you what you want, i.e. "just the file name/s". As opposed to reading the full file path and then extracting the "file name" component in the body of the for loop.

Example below that follows your original:

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

If you are running the script in the same directory as the files, then it simply becomes:

for filename in $(ls)
do
  echo $filename
done;

Solution 5 - Bash

if you want filename only :

for file in /home/user/*; do       
  f=$(echo "${file##*/}");
  filename=$(echo $f| cut  -d'.' -f 1); #file has extension, it return only filename
  echo $filename
done

for more information about cut command see here.

Solution 6 - Bash

You can either use what SiegeX said above or if you aren't interested in learning/using parameter expansion, you can use:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnthony MillerView Question on Stackoverflow
Solution 1 - BashSiegeXView Answer on Stackoverflow
Solution 2 - BashSean BrightView Answer on Stackoverflow
Solution 3 - BashOliver CharlesworthView Answer on Stackoverflow
Solution 4 - BashryanView Answer on Stackoverflow
Solution 5 - BashjosefView Answer on Stackoverflow
Solution 6 - BashBehzadView Answer on Stackoverflow