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

Time:05-02

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 the Directory name and the file name of a bash script by bash on follow way ?

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

Wanted output:

/path5/bashfile.sh

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.

  • Related