1

I have a specific file at the root of my project. I have a command line app (suman) that knows where this file is located. Is there a command line switch I can feed to my command line app that can take me to project root.

Something like

suman --home or suman -h or suman --root

what can I write as routine for this command that will actually change the current directory of the parent shell which issued this command? I am not even sure if this is possible.

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • Here are some possible solutions - http://stackoverflow.com/questions/13753157/bash-script-to-change-parent-shell-directory – Alexander Mills Mar 28 '17 at 18:31
  • 1
    Maybe use an alias? Assign the alias to run the command line app you have and return the variable then cd to it. – mkingsbu Mar 28 '17 at 18:34

2 Answers2

2

You can use a (bash/shell) function for this:

suman() {
   cd ~/project
   command suman "$@"
   cd -
}
  • cd ~/project - changes directory to $HOME/project
  • command suman "$@" - runs actual suman command
  • cd - - changes directory back to where we were
Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • well, I don't always want to cd, I only want to cd to the project root when -h switch is passed – Alexander Mills Mar 28 '17 at 18:35
  • 1
    ok, see my updated answer. `cd -` in the end changes directory back. – anubhava Mar 28 '17 at 18:37
  • the one thing is - I am not sure how to store the project root value as an env variable, I would have to set that somehow, since it won't be passed as an argument – Alexander Mills Mar 28 '17 at 18:41
  • You can set project root in `~/.bashc` e.g. `export projectDir="$HOME/project"` then use `cd "$projectDir"` as first line in this function body. – anubhava Mar 28 '17 at 18:43
  • thanks yeah, this is for a library, looking for something that users can use, which is more automatic. – Alexander Mills Mar 28 '17 at 23:42
  • I think there is any manual step here. This function need to be defined only once and then it can be used by users. – anubhava Mar 29 '17 at 04:54
  • I was talking about setting the env variable which represents the project root - with many projects in the filesystem, that is not a good technique IMO – Alexander Mills Mar 29 '17 at 06:58
1

If you have an NPM project, you can do this

function npmcd {
   cd $(npm root) &&
   cd ..
}

put the above in ~/.bashrc

and you should be good to go

Wherever you are in your project, you can issue npmcd at the command line and it will take your terminal to the root of your project, pretty swift.

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817