Http://www.linuxidc.com/Linux/2008-09/15517.htm
In Linux, the PWD command and getcwd () function are commonly used to obtain directory paths. However, sometimes it is not easy to match common requirements. The problem comes from lightning. He wroteProgramPut it in a folder and hand it to the customer. There are several applications and files in this folder. The customer can put this folder in any directory, and then the customer uses the absolute path to run a program in the folder: /Program/A/B/C/D/E/folder/fgh. sh, run fgh in the customer. sh this program uses other files in the same folder as it:/Program/A/B/C/D/E/folder/1.txt.
In this way, you need to obtain the absolute path of its directory in the fgh. Sh program:/Program/A/B/C/D/E/folder. The PWD command can only get the current directory, that is, the directory where the program is running, but cannot get the directory where the program is located. Dirname exactly implements this function. You can use dirname $0 to parse the absolute path/Program/A/B/C/D/E/folder.
Later I thought about it. The dirname command is not very common and hard to remember. In general, you can also make judgments in the program. If the customer uses an absolute path to run the program, you can get the parameter, it is a long string of things/Program/A/B/C/D/E/folder/fgh. sh, and then parse the desired path name from this parameter:
Filename =/Program/A/B/C/D/E/folder/fgh. Sh
Filedirectory =$ {filename % /*.*}
Http://www.linuxforum.net/forum/showflat.php? Cat = & board = fig & number = 407084 & page = 46 & view = expanded & SB = 5 & O = all
Related documents.
Q:
For example, a shell file named KK. Sh may be executed in different directories,
I hope:
If you are executing/usr/bin/KK. Sh, you want to return/usr/bin
If/usr/sbin/KK. Sh is executed, you want to return/usr/sbin,
How can I compile the KK. Sh file?
A:
Use/usr/bin/dirname to parse the directory name
[Xyb @ test] $ Cat D. Sh
#! /Bin/sh
Textfile = 'dirname $ 0'/hello.txt
Echo $ textfile
[Xyb @ test] $./D. Sh
./Hello.txt
[Xyb @ test] $ mkdir Adir
[Xyb @ test] $ cp d. Sh Adir/
[Xyb @ test] $ Adir/D. Sh
Adir/hello.txt
[Xyb @ test] $
Vardir = 'dirname $0'
Or
Varpath r = $0