如何通过bash获取bash脚本的目录名和文件名?

How to get the Directory name and file name of a bash script by bash?

关注是已知的。可能有帮助:

获取 filename.extension 包括。完整路径:

脚本:/path1/path2/path3/path4/path5/bashfile.sh

#!/bin/bash

echo [=12=]

read -r

输出:

/path1/path2/path3/path4/path5/bashfile.sh

得到filename.extension:

脚本:/path/path/path/path/path/bashfile.sh

#!/bin/bash

echo ${0##*/}

read -r

输出:

bashfile.sh

问题:

如何通过bash获取bash脚本的目录名和文件名?

Script: `/path1/path2/path3/path4/path5/bashfile.sh`

想要的输出:

/path5/bashfile.sh

备注: 也许它是可能的,如果你从右边看,从 "/*/"

中删除所有左边

比第一个拟合方案短一点:

脚本:/path1/path2/path3/path4/path5/bashfile.sh

#!/bin/bash

n=$(($(echo [=10=] | tr -dc "/" | wc -m)+1))
echo "/""$(echo "[=10=]" | cut -d"/" -f$(($n-1)),$n)"

read -r

输出:

/path5/bashfile.sh

也许它们是更短的解决方案。

readlink -f [=10=] |awk -F"/" '{print "/"$(NF-1)"/"$NF}'
# or
awk -F"/" '{print "/"$(NF-1)"/"$NF}' <(readlink -f [=10=])
# or 
awk -F"/" '{print "/"$(NF-1)"/"$NF}' <<<$(readlink -f [=10=])
# or
sed -E 's/^(.*)(\/\w+\/\w+\.\w+$)//g' <(readlink -f [=10=])

输出

/path5/bashfile.sh
#!/bin/bash

echo "/$(basename "$(dirname "[=10=]")")/$(basename "[=10=]")"
echo
echo

read -r

输出:

/Dirname/Filname.Extension