want only file names (not whole path) in shell script

hi i wrote following script,
#!/usr/bin/sh
for index in `ls /tmp/common/*.txt`
do
echo "$index"
done

here index is giving full path but in my program i want only file names (not along with whole path)

Eg. if in /tmp/common files are a.txt and b.txt den out should be a.txt b.txt

and not like ==> /tmp/common/a.txt /tmp/common/b.txt

any knows how to do it?

use basename command.

man basename

BASENAME(1)                      User Commands                     BASENAME(1)

NAME
       basename - strip directory and suffix from filenames

SYNOPSIS
       basename NAME [SUFFIX]
       basename OPTION

DESCRIPTION
       Print  NAME with any leading directory components removed.  If specified, also remove
       a trailing SUFFIX.

       --help display this help and exit

       --version
              output version information and exit

EXAMPLES
       basename /usr/bin/sort
              Output "sort".

       basename include/stdio.h .h
              Output "stdio".

echo `basename $index`

echo "$index" | cut -d"/" -f4

But this will only work for the example you provided - that has that specific number of / characters in the fully qualified path.

use ksh variable substitution:

echo ${file##*/}
#!/bin/ksh

a="/a/b/c"

file=${a##*/}
dir=${a%/*}

echo "a->[${a}] dir->[$dir] file->[${file}]"

thanks a lot ! :slight_smile: