Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have about 40 symbolic links in a directory that look like this:

lrwxr-xr-x    1 anna  staff    45B 22 Jun 11:20 menu-bg-left.jpg -> ../../../../../hg/www/images/menu-bg-left.jpg
lrwxr-xr-x    1 anna  staff    46B 22 Jun 11:20 menu-bg-right.jpg -> ../../../../../hg/www/images/menu-bg-right.jpg

I would like to change them all to a different directory:

lrwxr-xr-x    1 anna  staff    45B 22 Jun 11:20 menu-bg-left.jpg -> ../../../../../code-local/www/images/menu-bg-left.jpg
lrwxr-xr-x    1 anna  staff    46B 22 Jun 11:20 menu-bg-right.jpg -> ../../../../../code-local/www/images/menu-bg-right.jpg

For various reasons I can't just symlink the hg directory to the code-local directory, I need to change the links themselves.

Can I shell script this somehow?

share|improve this question

2 Answers 2

You change dir to the directory where you want your sym-links to be placed. Then you read all your images from the source directory in a for loop. With every run of the loop a sym-link is created.

Note: I couldn't test the script but should be fine. Check it first or someone can review it first

#!/bin/bash
cd /to/directory/where/symlinks/should/be
for file in ls /to/directory/where/symlinks/should/be
do
   rm $file
   ln -s /where/your/image/files/are/$file $file
done
share|improve this answer
    
No sorry, it's not that simple. I have directory X with many images and some symlinks. I have directory Y with many, many images. I want to update the existing symlinks in X to point to Y (not add new symlinks as would happen if I listed all the images in Y). –  Richard Jul 14 '11 at 14:35
    
i've edited the code, so the for loop now read the dir with the existing symlinks, than removes the first one, creates it again with the new path and so on and on. I think this is now what you need? –  Layticia Jul 14 '11 at 14:39
    
'fraid not, directory X has many images and some symlinks, I only want to replace the symlinks. Thanks anyway. –  Richard Jul 17 '11 at 17:53

You can use a combination of readlink and shell, something like:

#!/bin/sh
cd /to/directory/where/symlinks/should/be
for i in * ; do
    if [ -h $i ]; then
        NEWTARGET=`readlink $i | sed 's,old/path/to/files,new/path/to/files,'`
        rm -f $i
        ln -s $NEWTARGET $i
    fi
done
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.