1

如果我在 bash shell 中运行以下命令:

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

它输出file.txt,一切都很好。

如果在我的脚本中我有:

echo $1:t

它输出 /path/to/file.txt:t

根据我在 shell 中看到的行为,如何让它输出 file.txt?提前致谢。

4

3 回答 3

2

使用参数扩展语法:

echo ${1##*/}
于 2011-01-28T23:17:42.440 回答
1

在 bash 中,您可以使用${1##*/}扩展来获取文件的基本名称,并删除所有前导路径组件:

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

您也可以在脚本中使用它:

#!/bin/sh

echo "${1##*/}"

虽然${1##*/}当 Bash 被称为 as 时会起作用/bin/sh,但其他 Bash 功能需要您#!/bin/bash在脚本开始时使用。这种表示法在其他 shell 中也可能不可用。

一个更便携的解决方案是:

#!/bin/sh

echo `basename "$1"`
于 2011-01-28T23:17:55.723 回答
1

修饰符仅适用于词指示符

于 2011-01-28T23:19:27.273 回答