I'm trying to create a convenience alias that will change directories and then start a node server in that directory. I have it working for the most part, there's just one little issue that I can't figure out.
When I set up my alias to just change the directory—in my ~/.bashrc
file— I get the expected behavior:
alias ta='cd /Users/scotty/Develop/Meteor/task-assist'
And what I mean by expected behavior is that when I run $ ta
in the terminal, it not only changes the directory, but I can also open new tabs in the terminal and that directory carries over to the new tabs.
But for some reason when I add an additional command onto that alias to start a node server, and after running $ ta
again, the current directory does not carry over to the new terminal tabs (new tabs just open at root). The directory changes and the server starts, but it's like the changed directory is not actually set in the terminal. When I kill the server ctrl +c
, only then does the directory update in the terminal. I've tried both an alias and function to get this to work, but without success:
### meteor is the command that starts the server
alias ta='cd /Users/scotty/Develop/Meteor/task-assist && meteor'
### Also tried a function
ta(){
cd /Users/scotty/Develop/Meteor/task-assist
meteor
}
It's almost as if changing the directory and running meteor need to be two separate commands in order for new terminal tabs to open with that current working directory. And just to reiterate and further clarify, when I'm in the terminal and run $ta
and then press cmd + t
to open a new tab, I would like the new tabs current directory to be: /Users/scotty/Develop/Meteor/task-assist
.
Any ideas on how I can make this happen with an alias?
Best Answer
You have to go another way. Add a line at the end of your
.bashrc
that changes directory in the last directory the previous bash instance had asCWD
(current working directory).A line like this worked for me:
Explanation:
cd $(...)
: changes directory to whatever is determined belowreadlink /proc/$(...)/cwd
: reads the link where/proc/pid/cwd
points to (current working directory)echo -n $(...)
: removes the trailing newlineps -u $(whoami) -eo stat,pid,cmd
: shows my process in a simple formatawk '$3 == "'$(which bash)'" && $1 ~ /\+/{print $2}'
if it's abash
andbash
is in the foreground process group (indicated by the+
in thestat
field), then print the pidsort | head -1
we want only the lowest pidEdit:
In your case this might be a better solution:
It determines the pid of the newest instance of
meteor
and changes to this current working directory.