2

I have I symlink named CURRENT pointing to a directory , lets say

CURRENT -> $HOME/local/java/jdk1.8.0

I want to extract the jdk1.8.0 part as a string.

First, I get the directory by :

 current_dir= $(readlink -f $CURRENT)

And then, I tried to extract the last part of the path :

last_part= ${current_dir##*/}

or even when I try to print it via :

echo $current_dir

I get this error:

bash: /home/tarrsalah/local/java/jdk1.8.0: Is a directory

How can I convert a directory to a string ?

Salah Eddine Taouririt
  • 24,925
  • 20
  • 60
  • 96
  • 1
    Your errors occur due to the space following the equal sign: there must be **no** whitespace around the equal in shell variable assignment. – glenn jackman May 09 '13 at 19:31
  • Thanks @glennjackman , I prefer using `basename` , less error prone. – Salah Eddine Taouririt May 09 '13 at 19:37
  • ok, although my comment refers to a very fundamental aspect of shell programming which you appear to have trouble with. – glenn jackman May 09 '13 at 19:38
  • yes, I can see, this is my first shell script :) ,I will pay attention for this case, Thanks again. – Salah Eddine Taouririt May 09 '13 at 19:51
  • Good, it seems very useful, thanks @thatotherguy – Salah Eddine Taouririt May 09 '13 at 22:02
  • The actual problem is the space after the `=` signs in the code. When you run: `current_dir= $(readlink -f $CURRENT)`, it first runs the `readlink` command, obtaining the pathname. That output is then used as a command name, but the variable `current_dir` is set to empty in its environment before it is run. Of course, since the name is actually a directory, `bash` reports '... is a directory'. Do not put spaces around assignments in shells. – Jonathan Leffler May 12 '13 at 22:49

1 Answers1

6

Use basename:

$ basename /home/tarrsalah/local/java/jdk1.8.0
jdk1.8.0
piokuc
  • 25,594
  • 11
  • 72
  • 102