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

Follow are known. Possible it helps:

Get the filename.extension incl. fullpath:

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

#!/bin/bash

echo $0

read -r

Output:

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

Get filename.extension:

Script: /path/path/path/path/path/bashfile.sh

#!/bin/bash

echo ${0##*/}

read -r

Output:

bashfile.sh

Question:

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

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

Wanted output:

/path5/bashfile.sh

Remark: Perhaps its possible, if you look from right side, remove all left from "/*/"



Solution 1:[1]

#!/bin/bash

echo "/$(basename "$(dirname "$0")")/$(basename "$0")"
echo
echo

read -r

Output:

/Dirname/Filname.Extension

Solution 2:[2]

Little bit shorter than the first fitting solution:

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

#!/bin/bash

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

read -r

Output:

/path5/bashfile.sh

Perhaps they are a shorter solution.

Solution 3:[3]

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

output

/path5/bashfile.sh

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3