当前位置:网站首页>5. read the specified pathname -dirname

5. read the specified pathname -dirname

2022-06-11 10:38:00 Qimu king · Prince

1. brief introduction

dirname The command reads the specified pathname and deletes the last “/”( Slash ) And the characters after it , Keep the rest , And write the results to the standard output . If the last one “/” No characters after ,dirname The command uses the penultimate “/”, All subsequent characters are ignored .

Example :

1) dirname /etc/init.d/acpid -> /etc/init.d
2) dirname /etc/init.d/ -> /etc
3) dirname /etc/init.d -> /etc
4) dirname stdio.h -> .
5) dirname dir1/str dir2/str  -> "dir1" followed by "dir2"

2. example

In many shell Script , You can often see the following statements

rootDir=$(cd $(dirname $0); pwd)

The purpose of this statement is to obtain shell The absolute path of the directory where the script is located , How to understand this sentence ? Why not use it directly pwd To get the current path ?

"." Represents the current path 
$0, This is a bash shell Positional parameters in the script , Used to indicate the command itself entered into the command line .
 The rest are $1,$2 wait , Represents the first parameter and the second parameter after the command entered into the command line respectively 
bash test.sh 10 9
 Among them $0 Namely test.sh,10 and 9 Namely $1 and $2.
pwd, This command prints the current absolute path .

Why not pwd?

Please pay attention to the basic facts

 call shell Script , It is under the current directory of the calling script , Execute every command in the script line by line .

Modify the above script as follows

#/bin/bash
rootDir=$(cd $(dirname $0); pwd)
echo "rootDir $rootDir"
echo "pwd $pwd"

And in ~/lyq Enter the command code/test.sh To run this script , The output is as follows

[email protected]:~/lyq$ code/test.sh
rootDir /home/usr/lyq/code
pwd /home/usr/lyq

The first 2 individual pwd Not the directory where the script is located , It's the directory where we type the command . As that basic fact shows , Running the script in this directory is equivalent to typing in each sentence of the script line by line and executing it , So in ~/lyq Call... In the script pwd, It is equivalent to typing in the directory pwd, So the result is the current path .

The reason why it can't be used directly pwd Get the directory where the script is located , Because if the script is called outside the script Directory , It returns the directory where the command is called, not the directory where the script is located .

3. expand


#/bin/bash
topDir = $(cd $(dirname $0); cd ../; pwd) # Get the current path , Switching path , And print 
echo topDir

$(topDir)/Build/build_app.bat
原网站

版权声明
本文为[Qimu king · Prince]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111030210258.html