Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I often want to change into the directory of a file on my file system, but I'm not sure where the file is.

I search for it like so:

find -type f -name "myfile.txt"

Lets say for the sake of simplicity, that this returns one result, eg.

/some/super/long/path/that/i dont/want/to/type/myfile.txt

I then usually type this:

cd $(dirname $(!!))

To switch into the directory of the file I was searching for....

Is there anyway to put this into a shell script or alias, so I can basically type:

cdlast

and it runs:

cd $(dirname $(!!))

using the shell's HISTORY? I've tried it, and the shell history seems to be missing in bash scripts.

share|improve this question
3  
You are misusing find: find -type f -name "myfile.txt" –  Bernhard Apr 23 '13 at 17:41
    
i played around a bit, and think you're right... find -name "myfile.txt" is short enough for me, and will be faster... thanks ;-) –  Brad Parks Apr 24 '13 at 12:33

3 Answers 3

up vote 4 down vote accepted

fc -s runs the previous command again:

alias cdlast='cd "$(dirname "$(fc -s 2> /dev/null)")"'

Or use eval "$(history -p !!)":

alias cdlast='cd "$(dirname "$(eval "$(history -p !!)")")"'
share|improve this answer

You can use an alias.

alias cdlast='cd "$(dirname "$(eval $(history -p !!))")"'

Make sure you have the double quotation marks in there. Those prevent the results of the command substitutions from being split into separate words if they have spaces and interpreted as wildcard patterns if they have special characters such as * and ?.

share|improve this answer

I'd use a function:

gotofile () { pushd "$(find . -name "$1" -printf "%h\n")"; }

Change "." to some directory as appropriate ("~" perhaps)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.