Adding shortcut(soft-link) of a directory to global PATH so that it can be accessed from everywhere

StackOverflow https://stackoverflow.com/questions/23575853

Question

I'm trying to put all my symlinks in one directory (I'll call this symlinks directory). I've exported the path of that directory and put it in my .bashrc file. The symlinks to executable applications are running fine but I'm having hard time making symlinks for my directory. This is what I tried.

ln -s ~/mydir/ m 

where m is supposed to be my symlink to mydir directory.

This works only when I'm inside symlinks directory. Trying cd m or even just m didn't work from outside that directory. I get:-

bash: cd: m: No such file or directory

Okay, so I thought maybe the PATH doesn't recognize directory paths. So I tried creating a bash script.

#!/bin/sh
cd ~/mydir/

Tried this, m...permission denied. Okay I thought and did chmod +x m to that file. And when I run that script like m then nothing. I tried ./m, still nothing.

I'm close to losing my mind to do such a simple task.

Was it helpful?

Solution

PATH is used to look for commands and I think a command ought to be a file or a symlink to a file.

So, cd m doesn't work as here the command is "cd" (not m). The lookup for "m" does not happen in PATH.

Just m does not work as the "m" found in PATH is a link to a directory and not a file. You can try creating another "m" which points to a file and put it in a directory later in the PATH and it will be recognized when you run just m.

The script you created does work, except that the cd now happens in a new shell and is lost at the end of the script. You can check this by putting an ls after the cd in your script.

There are a few ways to achieve what you want to do.

One option is to use the CDPATH variable. This is the search path for the cd command. Check man bash for details but basically, all you need to do is add your symlinks directory to CDPATH.

export CDPATH=~/symlinks:$CDPATH
cd m   ## will cd to linked directory

Alternatively, you can create aliases or functions and put it in your .bashrc or another file which you then source.

alias m="cd ~/mydir"

m() {
    cd ~/mydir
}

And now you can just type m to cd to mydir

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top