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 "/*/"
CodePudding user response:
You could translate from this C code:
#include <libgen.h>
#include <string.h>
char* local_file = "/foo/bar/baz.txt";
char* ts1 = strdup(local_file);
char* ts2 = strdup(local_file);
char* dir = dirname(ts1);
char* filename = basename(ts2);
CodePudding user response:
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.
CodePudding user response:
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
CodePudding user response:
#!/bin/bash
echo "/$(basename "$(dirname "$0")")/$(basename "$0")"
echo
echo
read -r
Output:
/Dirname/Filname.Extension