0

I recently upgraded my computer and along with a new OS I have a new username. Because of that I have a References directory full of links that don't work anymore, but they would if I could simply swap out my old username for my new one within the links.

For example: The file /home/CurUserName/Reference/C/Car/Insurance points to /home/OldUserName/Reference/I/Insurance

I found this answer which explains how to find every link in a directory, and I've found elsewhere online instructions on how to manually update a single link, but I'm not experienced enough with Bash to figure out how (or if) I can change all of them at once. Is this possible? If so, how?

0

This question should probably be under unix/bash, but here you go:

#!/bin/bash

# renl: Rename links

# Make sure we have at least two arguments, the source and destination
if [ $# -lt 2 ];then
    echo Usage: renl SOURCE DEST [TARGET]
    exit 1
else
    export SOURCE="$1"
    export DEST="$2"
fi

# Setup the target directory argument
if [ -n "$3" ]; then
    export TARGET="$3"
else
    export TARGET="."
fi

# Output the input values
echo "Source: $SOURCE"
echo "Destin: $DEST"
echo "Target: $TARGET"
echo

# Loop thru all links in the target directory
links=$(find $TARGET  -maxdepth 1  -type l)
for f in $links; do
    tolink=$(readlink "$f")

    if [[ $tolink == *"${SOURCE}"* ]]; then
        newlink=${tolink/$SOURCE/$DEST}
        echo "$f --> $tolink ==> $newlink"
        # Uncoment the next line to actaully do the rename
        # rm "$f" && ln -s "$newlink" "$f"
    else
        echo "$f --> $tolink"
    fi
done;

unset SOURCE
unset DEST
unset TARGET

Note that you'll have to input any wildcards for TARGET with single quotes around it if you don't want the shell expansion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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