4

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.

  • 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
4

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 !!)")")"'
3

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 ?.

2

I'd use a function:

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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