bashshreadlink

Resolving path with bash


On I am on MacOS, but looking for a cross-platform solution that will also work on *nix. Simple question, how can I resolve this path with bash a script?

/Users/Olegzandr/.nvm/versions/node/v7.2.0/bin/../lib/node_modules/suman/cli/cli.sh

This path is made up of two pieces which I have in hand:

/Users/Olegzandr/.nvm/versions/node/v7.2.0/bin

and

../lib/node_modules/suman/cli/cli.sh

what is the best way to get an absolute path that represents the resolution of those two paths?

Note that my Mac has readlink on it, but it doesn't appear to be the same utility as that on *nix machine. Most importantly, my readlink utility does not have the -f option that *nix utility probably does, so I can't seem to use that.


Solution

  • bash is perfectly able to handle such a task. Taking inspiration from the main question comments, you can do something like this :

    MYPATH=/Users/Olegzandr/.nvm/versions/node/v7.2.0/bin/../lib/node_modules/suman/cli/cli.sh
    RESOLVED="$(cd $(dirname $MYPATH) && pwd)/$(basename $MYPATH)"
    

    EDIT: I gave this answer using tools i was familiar with. However, I've just taken a look at the readlink utility you mentioned in your question. It seems to work just fine for me with the -m option. Is this flag available on mac ?

    readlink -m /home/myusername/Documents/test_dir/dir_1/../dir_2/test.sh
    > /home/myusername/Documents/test_dir/dir_2/test.sh