What does "cd $ {0% / *}" mean in bash?

I came across a git commit that clears some readlink and dirname commands with this replacement of the magic variable cd ${0%/*} .

How to bash interpret it?

+12
source share
2 answers

% here is called the pattern matching operator.

Quote from the book โ€œLearning the Bash Shellโ€:

The classic use of pattern matching operators is to remove path name components, such as directory prefixes and file name suffixes. With that in mind, here is an example that shows how all operators work. Assume the path variable has the value /home/cam/book/long.file.name ; then:

 Expression Result Comments ${path##/*/} long.file.name ## takes out longest matched substring from the front ${path#/*/} cam/book/long.file.name # takes out shortest matched substring from the front $path /home/cam/book/long.file.name ${path%.*} /home/cam/book/long.file % takes out shortest matched substring from the rear ${path%%.*} /home/cam/book/long %% takes out longest matched substring from the rear 

They can be difficult to remember, so here is a handy mnemonic device:

  • # matches the front because numeric characters precede numbers;
  • % matches the rear because percent signs follow numbers.

In your particular case, 0 is an analogue of path in my example, so you should know this.

If $0 is equal to /home/chj/myfile.txt , then cd ${0%/*} will expand to cd /home/chj , that is, the "file" part will be deleted.

I understand your desire to ask this question, because it is too difficult to find the answer without spending several hours studying the Bash book.

+12
source

The cd ${0%/*} changes the directory to the directory containing the script, assuming $0 set to the fully qualified script path.

+9
source

Source: https://habr.com/ru/post/983410/


All Articles