bashsubstitutionreadlink

how to filter a command subsitution from the resulting value of a readlink for symlink?


This may be poorly titled as I'm not fully sure what the process is called. Basically I want to get only the last part of a symlink path, and I'm trying to use the same method I use with PWD.

For example: if I do

PWD

it prints

/opt/ct/mydir

if I do

echo ${PWD##*/}

it prints only the last part

mydir

So using that design I can do

readlink mysymlink

which gives

/opt/ct/somedir

and I can do

TMP=$(readlink mysymlink)
echo ${TMP##*/}

and it will print

somedir

So now how can I combine that last part into one line like

 TMP=$(readlink mysymlink && echo ${TMP##*/})

???

The example I show gives me 2 concatenated results.. one with the full path and one with just the part I want. I only want that last directory.

I also tried

TMP=${ $(readlink mysymlink)##*/}

to no avail


Solution

  • Variable substitution suffixes can only be used with variables, not command substitutions. You either have to set the variable and modify it in separate statements, as in your first attempt, or use additional command substitutions:

    TMP=$(basename $(readlink))