1 basename
basename var [suffix]
# 从路径中提取出文件名(带后缀) var=/dir1/dir2/dir3/file1.txt echo $(basename ${var}) # 从路径中提取出文件名(不带后缀) var=/dir1/dir2/dir3/file1.txt echo $(basename ${var} .txt)
2 dirname
从路径中提取出目录名;
dirname var
# 提取文件所在路径 var=/dir1/dir2/dir3/file1.txt echo $(dirname ${var})
注:
basename和dirname命令不是完全有效的,实际上是对最后一个文件或目录进行文件名和目录名的提取,而非真正识别最后一个是否为文件;
var=/dir1/dir2/dir3/dir4 echo $(basename ${var}) # 输出:dir4 var=/dir1/dir2/dir3/dir4 echo $(dirname ${var}) # 输出:/dir1/dir2/dir3