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 i开发者_JS百科n a shell? Thanks in advance.
Use the parameter expansion syntax:
echo ${1##*/}
Modifier only work on word designators
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"`
精彩评论