Stupid Bash Tricks: Copy The Working Directory
Published 29 April 08 by Justin French
The Problem
I have a Terminal window open, I’m doing stuff and I want to open another Terminal window or tab to the same current working directory.
A Possible Solution
I recently added this to my ~/.bash_login file:
alias cwd='pwd | pbcopy'
This might be stating the obvious, but pwd outputs the current working directory, and we pipe that into pbcopy which copies that output to the paste board. I choose cwd (Copy Working Directory) as the alias, your mileage may vary.
It’s still a bit fiddly, but better than grabbing the mouse to copy the current working directory:
- type
cwd - type Command-T (new tab in Terminal.app)
- type
cd - type Command-V (Paste)
Can you better?
Ideally I’d like to get this down to one key-stroke. Automator’s “Watch Me Do” recordable action was looking promising, but it runs horribly slow. Applescript maybe? Email me or go nuts in the comments!
Update 1:
Benjamin Birnbaum writes in with this bash function. There’s still some lag (AppleScript lag I guess) but I’m suitably impressed!
Update 2:
Chap Lovejoy writes in with this AppleScript which I’m yet to try out:
tell application "Terminal"
activate
set wnd to the front window
set tb to the selected tab of wnd
-- We don't want to clobber any running process
if not busy of tb then
-- Clear the current command line
tell application "System Events"
keystroke "a" using control down
keystroke "k" using control down
end tell
do script "pwd | pbcopy" in tb
-- The make comamnd in Terminal appears to be
-- broken so generate the keystroke as a workaround
tell application "System Events"
keystroke "t" using command down
end tell
do script "cd \"`pbpaste`\"" in the selected tab of wnd
end if
end tell