Sunday, May 15, 2022

[FIXED] How do I delete all child directories not pointed at by a symlink?

Issue

I’m using bash shell on Ubuntu 16.04. I have a symlink set up like so

$ ls -al /home/myuser/web/current
lrwxrwxrwx 1 myuser myuser 40 Feb 25 15:49 /home/myuser/web/current -> /path/to/main/releases20220225152608

The “releases” directory contains several other directories

$ ls /path/to/main/releases
20220223111602
20220224122838
20220225152608

How would I delete all other child directories in “/path/to/main/releases“ that are not pointed at by the symlink, “/home/myuser/web/current”?


Solution

Try

for dir in /path/to/main/releases/*/; do
    [[ $dir -ef /home/myuser/web/current ]] || echo rm -r -- "$dir"
done
  • The [[ $path1 -ef $path2 ]] test checks if the two paths refer to the same item (file, directory, fifo, ...) on disk, regardless of what links (hard or soft) are traversed in either path.
  • Remove the echo if you are happy that the resulting code will do what you want.


Answered By - pjh
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.