Bash – Creating an alias to Change Directory and have that directory be the current working directory in new terminal tabs

aliasbashcd-command

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 as CWD (current working directory).

A line like this worked for me:

cd $(readlink  "/proc/$(echo -n $(ps -u $(whoami) -eo stat,pid,cmd | awk '$3 == "'$(which bash)'" && $1 ~ /\+/{print $2}' | sort | head -1))/cwd")

Explanation:

  • cd $(...): changes directory to whatever is determined below
  • readlink /proc/$(...)/cwd: reads the link where /proc/pid/cwd points to (current working directory)
  • echo -n $(...): removes the trailing newline
  • ps -u $(whoami) -eo stat,pid,cmd: shows my process in a simple format
  • awk '$3 == "'$(which bash)'" && $1 ~ /\+/{print $2}' if it's a bash and bash is in the foreground process group (indicated by the + in the stat field), then print the pid
  • sort | head -1 we want only the lowest pid

Edit:

In your case this might be a better solution:

cd $(readlink /proc/$(pgrep -n meteor)/cwd)

It determines the pid of the newest instance of meteor and changes to this current working directory.

Related Question