General TC > Programming & Scripting - Unofficial

Changing to a links parent directory

(1/1)

Rich:
I was ask about a command I posted and decided to share the answer here in case anyone else is interested.

The (paraphrased) question was:

--- Quote ---Why did you use:

--- Code: ---cd `readlink /etc/sysconfig/tcedir`/../
--- End code ---
Why not cd /etc/sysconfig/tcedir/ ?
--- End quote ---

Good question. The answer is because I wanted to go to the parent directory of  tce.  If you try to do that with the link directly, here's
what happens:

--- Code: ---tc@E310:~$ cd /etc/sysconfig/tcedir
tc@E310:/mnt/sda1/tce$ cd ../
tc@E310:/etc/sysconfig$
--- End code ---
Instead of moving up 1 level from the  tce  directory, I moved up 1 level from the  tce  link to  /etc/sysconfig.

In fact, even though the path shown in the command prompt says  /mnt/sda1/tce , the  pwd  command and  $PWD  variable
say otherwise:

--- Code: ---tc@E310:~$ cd /etc/sysconfig/tcedir
tc@E310:/mnt/sda1/tce$ pwd
/etc/sysconfig/tcedir
tc@E310:/mnt/sda1/tce$ echo $PWD
/etc/sysconfig/tcedir
tc@E310:/mnt/sda1/tce$
--- End code ---

The readlink  command returns the value or text that the link represents instead of following the link:

--- Code: ---tc@E310:~$ readlink /etc/sysconfig/tcedir
/mnt/sda1/tce
tc@E310:~$
--- End code ---

The  back ticks  cause the result of a command to be returned. Here is an example, first without and then with  back ticks:

--- Code: ---tc@E310:~$ echo readlink /etc/sysconfig/tcedir
readlink /etc/sysconfig/tcedir
tc@E310:~$
tc@E310:~$ echo `readlink /etc/sysconfig/tcedir`
/mnt/sda1/tce
tc@E310:~$
--- End code ---

So by using  readlink  my command changed to the absolute location instead of following the link. I could have done this instead:

--- Code: ---cd `readlink /etc/sysconfig/tcedir`
cd ../
--- End code ---

There may well be other ways of getting there, but this is what came to mind.

hiro:
thank you. good idea to answer on the forum, it has more educative value than i thought :)

Navigation

[0] Message Index

Go to full version