Try
parent_path=$(echo "$current_path"/ | sed -e "s|[^/]||g" -e "s|/|../|g")
cd "${current_path}" ; ln -s "${parent_path}${parent_file_to_link}"
This works simply by counting the slashes in "${current_path}".
The desired depth is one more than the number of slashes
(e.g., the depth of test/dir/hello, which contains two slashes, is 3),
so we simply add a slash: echo "$current_path"/. Pipe it into sed.
Since we’re manipulating slashes, it’s easier to use a character other than /
as the delimiter for sed’s s command; I like to use the vertical bar (|).
s|[^/]||g finds all characters that are not slash
and replaces them with nothing.
In other words, it deletes all characters except for the slashes.
So, for the "${current_path}" value of test/dir/hello,
we echo’d test/dir/hello/ and then chopped that down to ///.
Then s|/|../|g" changes every / into ../, so we end up with ../../../.
Note: this assumes that "${current_path}"
does not have any excess (unnecessary) slashes in it.
For example, test/dir//hello and test/dir/hello/
are logically equivalent to test/dir/hello,
but they contain a misleading number of slash characters,
which will corrupt this process.
P.S. Always quote all shell variables unless you have a reason not to
and you’re sure you know what you’re doing. Using braces
(as in ${variable_name}) is not the equivalent to quoting.
ln's-roption. Withbash -O extglob, see${current_path//+([^\/])/..}/home/kostas/test/dir/hello/link -> /home/kostas/file/to/linkactually expressed as a relative link/home/kostas/test/dir/hello/link -> ../../../file/to/link?