View Full Version : How to get folder that a file is in with a shell script?
maybeway36
March 29th, 2008, 03:53 PM
I have a shell script that launches kdialog to find a file to open. I want the next program to run in the same directory as that file, so if the file is ~/Documents/file.txt it should run in ~/Documents. I'm sure this can be done by taking off the last slash and everything after it, but how?
dwhitney67
March 29th, 2008, 04:51 PM
Will something like the following work for you?
basename `find . -name someFile.txt`
Alternatively,
basename /some/path/to/a/file.txt
maybeway36
March 29th, 2008, 08:26 PM
I really want to do the complete opposite of basename, i.e. find the directory.
stroyan
March 29th, 2008, 08:41 PM
The opposite of basename is dirname.
Or, you can just use a bash feature to strip off the last / and trailing chars.
The second way would be a bit faster.
$ F='~/Documents/file.txt'
$ echo $(dirname "$F")
~/Documents
$ echo ${F%/*}
~/Documents
WW
March 29th, 2008, 08:54 PM
If you use the bash parameter substitution, you must be sure that the file has at least one slash in it. Otherwise...
$ F="file.txt"
$ dirname $F
.
$ echo ${F%/*}
file.txt
$
dirname gives a correct directory ("."), but ${F%/*} gives the original file name.
maybeway36
March 29th, 2008, 11:02 PM
Thanks! Since my script gets the file path from kdialog, I think I'll just use ${F%/*} in my script.
ghostdog74
March 30th, 2008, 03:21 AM
you can also get the path using GNU find
find /fullpath -name "file*" -printf "%h\n"
Mr. C.
April 1st, 2008, 05:46 AM
I presume kdialog presents you with a full pathname. If so, just use dirname as indicated earlier.
If kdialog only gives you a relative path, the job is more difficult.
The find solution presented above is problematic in that a) it takes a very long time, b) does not guarantee file uniqueness.
Powered by vBulletin® Version 4.2.2 Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.