Just how do I divided the $0 variable to locate directory site and also loved one courses in bash?

The $0 variable has the course details of the manuscript.

  • Just how can I transform the course details to outright course? I suggest just how to refine ~,.,. or comparable?
  • Just how can I divide the course details right into directory site and also documents name?

I can make use of python/perl for this, yet I intend to make use of bash when possible.

2019-05-07 01:29:50
Source Share
Answers: 3

Using dirname and also basename like stated by Michael needs to be the most safe means to get what you desire.

Anyhow if you actually intend to do this with "bash just devices" you can make use of parameter replacement :

echo `basename $PWD`        # Basename of current working directory.
echo "${PWD##*/}"           # Basename of current working directory.
echo `basename $0`          # Name of script.
echo $0                     # Name of script.
echo "${0##*/}"             # Name of script.
echo "${filename##*.}"      # data
                            # Extension of filename.

This instance is straight extracted from the Advanced Bash Scripting Guide which deserves an appearance.

The description is rather straightforward :

$ var #Pattern Remove from $var the fastest component of $Pattern that matches the front end of $var. $ var ## Pattern Remove from $var the lengthiest component of $Pattern that matches the front end of $var.

Consider the pattern like some regex and also the # or ## as some sort of greedy/non - hoggish modifier.

This could come to be valuable if you will certainly need to do some extra difficult removals of a courses component.

2019-05-08 22:35:43

realpath is a command which informs you the actual course (gets rid of. and also symbolic web links etc)

It is typical with FreeBSD. According to this conversation it's additionally readily available for Linux :


That conversation additionally supplies a bash remedy :

$ bash -c "cd /foo/../bar/ ; pwd"
2019-05-08 22:16:30

You do not require to refine points like ~, the covering does it for you. That's why you can pass ~/filename to any kind of manuscript or program and also it functions - - all those programs do not take care of ~ themselves, your covering transforms the argument to /home/username/filename and also passes that to the program rather :

$ echo ~/filename

If you require an approved filename (one that does not include points like ..), usage realpath (many thanks Neil) :

$ realpath ~/../filename

As for splitting the course right into directory site name and also filename, usage dirname and also basename :

$ dirname /foo/bar/baz

$ basename /foo/bar/baz
2019-05-08 21:32:32