I have following folder structure created via mkdir -p foo subdir/bar && ln -s subdir/bar bar
├── bar -> subdir/bar
├── foo
└── subdir
└── bar
when working in bar folder: How can I resolve/expand a relative path (../foo)?
user@mypc:/work/bar$ realpath -e ../foo # result: "realpath: ../foo: No such file or directory"
user@mypc:/work/bar$ realpath -m ../foo # result: "/work/subdir/foo"
user@mypc:/work/bar$ realpath -L ../foo # result: "/work/subdir/foo"
user@mypc:/work/bar$ readlink ../foo # result: ""
user@mypc:/work/bar$ readlink -f ../foo # result: "/work/subdir/foo"
user@mypc:/work/bar$ readlink -m ../foo # result: "/work/subdir/foo"
What can I do to get absolute path /work/foo from relative path ../foo?
Edit1: Unfortunately it even becomes more tricky if I only have a variable MYPATH which I do not know if it is relative or absolute.
user@mypc:/work/bar$ MYVAR="../foo"
user@mypc:/work/bar$ realpath -L "$PWD/$MYVAR" # result: "/work/foo"
user@mypc:/work/bar$ MYVAR="/work/foo"
user@mypc:/work/bar$ realpath -L "$PWD/$MYVAR" # result: "realpath: /work/bar//work/foo: No such file or directory"
What can I do to get absolute path /work/foo from variable MYPATH (which might be set to ../foo or /work/foo?
Based on your directory layout:
If you get a not found error, it means that the directory really does not exist. That's why I propose to check this before.
However, your setting is a bit confusing in that you have two
bardirectories. Make sure that you apply the correct relative path when callingrealpath.