WelcomeWelcome | FAQFAQ | DownloadsDownloads | WikiWiki

Author Topic: Changing to a links parent directory  (Read 2008 times)

Online Rich

  • Administrator
  • Hero Member
  • *****
  • Posts: 11573
Changing to a links parent directory
« on: January 28, 2020, 10:17:09 AM »
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: [Select]
cd `readlink /etc/sysconfig/tcedir`/../Why not cd /etc/sysconfig/tcedir/ ?

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: [Select]
tc@E310:~$ cd /etc/sysconfig/tcedir
tc@E310:/mnt/sda1/tce$ cd ../
tc@E310:/etc/sysconfig$
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: [Select]
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$

The readlink  command returns the value or text that the link represents instead of following the link:
Code: [Select]
tc@E310:~$ readlink /etc/sysconfig/tcedir
/mnt/sda1/tce
tc@E310:~$

The  back ticks  cause the result of a command to be returned. Here is an example, first without and then with  back ticks:
Code: [Select]
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:~$

So by using  readlink  my command changed to the absolute location instead of following the link. I could have done this instead:
Code: [Select]
cd `readlink /etc/sysconfig/tcedir`
cd ../

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

Offline hiro

  • Hero Member
  • *****
  • Posts: 1229
Re: Changing to a links parent directory
« Reply #1 on: January 28, 2020, 06:29:11 PM »
thank you. good idea to answer on the forum, it has more educative value than i thought :)