Shell – Loop through a folder and list files

directoryfilesforshell-script

I have a folder named 'sample' and it has 3 files in it. I want to write a shell script which will read these files inside the sample folder and post it to an HTTP site using curl.

I have written the following for listing files inside the folder:

for dir in sample/*; do
        echo $dir;
        done

But it gives me the following output:

sample/log

sample/clk

sample/demo

It is attaching the parent folder in it. I want the output as follows (without the parent folder name)

log

clk

demo

How do I do this?

Best Answer

Use basename to strip the leading path off of the files:

for file in sample/*; do
    echo "$(basename "$file")"
done

Though why not:

( cd sample; ls )
Related Question