This article mainly introduces the Linux system to obtain the path of the file name method, the article summed up two, the need for friends can refer to the
The code is as follows:
[Root@dabu.info] #basename/root/aaa/bbb/dabu.txt
Show:
The code is as follows:
Dabu.txt #获取路径的文件名
How do I get the path to the script file in the shell script?
Method One:
The code is as follows:
[Root@dabu.info] #DIR =$ (CD "$ (dirname" $) "; pwd)
[Root@dabu.info] #echo $DIR
But like this dirname "$", you get the wrong result when you encounter the source command.
Method Two:
The code is as follows:
[Root@dabu.info] #echo "$ (CD" $ (dirname "${bash_source[0]}") "&& pwd)"
The above line command can get the absolute wheel path of the script, no matter where you call the script.
But if you have soft links, you won't be able to use them. So, in order to properly parse the soft link to the script, you can use the following multiline command:
The code is as follows:
Source= "${bash_source[0]}"
While [-H "$SOURCE"]; Do # resolve $SOURCE until the ' file is no longer a symlink
Dir= "$ (cd-p" $ (dirname "$SOURCE") "&& pwd)"
Source= "$ (readlink" $SOURCE ")"
[[$SOURCE!=/*]] && source= "$DIR/$SOURCE" # If $SOURCE is a relative symlink, we need to resolve it relative t o The path where the Symlink file was located
Done
Dir= "$ (cd-p" $ (dirname "$SOURCE") "&& pwd)"
can also be used with the SOURCE,BASH-C command
However, if you use a CD to switch to a different directory in your script, the commands above will not wait for the correct result when you run the command fragment above. You can refer to the article about the $cdpath trap. To understand how it works, you can run the following code:
The code is as follows:
#!/bin/bash
Source= "${bash_source[0]}"
While [-H "$SOURCE"]; Do # resolve $SOURCE until the ' file is no longer a symlink
Target= "$ (readlink" $SOURCE ")"
if [[$SOURCE = *]]; Then
echo "SOURCE ' $SOURCE ' an absolute symlink to ' $TARGET '"
Source= "$TARGET"
Else
Dir= "$ (dirname" $SOURCE ")"
echo "SOURCE ' $SOURCE ' is a relative symlink to ' $TARGET ' (relative to ' $DIR ')"
Source= "$DIR/$TARGET" # If $SOURCE is a relative symlink, we need to resolve it relative to the path where the symlink fi Le was located
Fi
Done
echo "SOURCE is ' $SOURCE '"
Rdir= "$ (dirname" $SOURCE ")"
Dir= "$ (cd-p" $ (dirname "$SOURCE") "&& pwd)"
If ["$DIR"!= "$RDIR"]; Then
echo "DIR ' $RDIR ' resolves to ' $DIR '"
Fi
echo "DIR is ' $DIR '"