1

If I run the following in a bash shell:

./script /path/to/file.txt
echo !$:t

it outputs file.txt and all is good.

If in my script I have:

echo $1:t

it outputs /path/to/file.txt:t

How can I get it to output file.txt as per the behaviour I see in a shell? Thanks in advance.

rich
  • 18,987
  • 11
  • 75
  • 101

3 Answers3

2

Use the parameter expansion syntax:

echo ${1##*/}
DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
1

In bash you can use the ${1##*/} expansion to get the basename of the file with all leading path components removed:

$ set -- /path/to/file
$ echo "$1"
/path/to/file
$ echo "${1##*/}"
file

You can use this in a script as well:

#!/bin/sh

echo "${1##*/}"

While ${1##*/} will work when Bash is called as /bin/sh, other Bash features require that you use #!/bin/bash at the start of your script. This notation may also not be available in other shells.

A more portable solution is this:

#!/bin/sh

echo `basename "$1"`
thkala
  • 84,049
  • 23
  • 157
  • 201
1

Modifier only work on word designators

mathk
  • 7,973
  • 6
  • 45
  • 74