Skip to main content
add missing quotes
Source Link
jordanm
  • 43.6k
  • 10
  • 121
  • 115

This is a common task that can be handled by a parameter expansion in any POSIX shell.

path=$HOME/Documents/test/one.txt
file=${path##*/} # file contains one.txt

Another common method is to use the basename program.

file=$(basename $path"$path")

The only disadvantage is having to spawn an external program. It's main advantage is that it properly handles paths with a trailing /.

This is a common task that can be handled by a parameter expansion in any POSIX shell.

path=$HOME/Documents/test/one.txt
file=${path##*/} # file contains one.txt

Another common method is to use the basename program.

file=$(basename $path)

The only disadvantage is having to spawn an external program. It's main advantage is that it properly handles paths with a trailing /.

This is a common task that can be handled by a parameter expansion in any POSIX shell.

path=$HOME/Documents/test/one.txt
file=${path##*/} # file contains one.txt

Another common method is to use the basename program.

file=$(basename "$path")

The only disadvantage is having to spawn an external program. It's main advantage is that it properly handles paths with a trailing /.

Source Link
jordanm
  • 43.6k
  • 10
  • 121
  • 115

This is a common task that can be handled by a parameter expansion in any POSIX shell.

path=$HOME/Documents/test/one.txt
file=${path##*/} # file contains one.txt

Another common method is to use the basename program.

file=$(basename $path)

The only disadvantage is having to spawn an external program. It's main advantage is that it properly handles paths with a trailing /.