Scott Hack
Scott Hack

Reputation: 33

Write a bash script to rm a directory and replace with a symlinked directory

I just found out that one of the plugins that is on my server has a security flaw and I'd like to delete all of those versions of the plugins. But I recently started learning how to run a single master copy of each plugin and WordPress itself by installing WordPress in a multi-tenant fashion.

Through some Googling I was able to find the correct command to search my server for all occurrences of the plugin name. So I've run find / -type d -name 'plugin_name' and now have a list of directories that look like /home/rentals/public_html/wp-content/plugins/plugin_name

I'm trying to create a bash script that will go through each line of the text file and then delete the directory that currently exists and then create a new directory that is symlinked to a different location.

My file looks like this:

/home/rentals/public_html/wp-content/plugins/all-in-one-seo-pack    
/home/beachcon/public_html/wp-content/plugins/all-in-one-seo-pack    
/home/sellingo/public_html/wp-content/plugins/all-in-one-seo-pack

My pseudo code looks something like this.

The truth though is that I only know some basic php and what I've been able to Frankenstein together here isn't far enough along. Can someone assist?

#!/bin/bash

cat myfile.csv | while read line
do
    rm -rf "$var1" && ln -s "$var1" "$symlink_directory"
done

Upvotes: 0

Views: 124

Answers (1)

Tom Fenech
Tom Fenech

Reputation: 74635

I think that this script does what you want. I was a little confused about which directory contained the folders to be deleted but hopefully the script is self-explanatory:

#!/bin/bash

# directory containing plugins to be removed
plugin_dir="/opt/wordpress/plugins/"

while read line
do
    # slice final part of directory name from line in file
    # (remove everything up to the final /)
    plugin_name=${line##*/}
    # full path to directory which will be removed
    dir="$plugin_dir/$plugin_name"
    # remove directory and create symbolic link to path from file
    rm -rf "$dir" && ln -s "$line" "$dir"
done < myfile

update

Based on your edits to the code, I think that this is a lot simpler than I first thought:

#!/bin/bash

# directory containing plugins to be removed
plugin_dir="/opt/wordpress/plugins/all-in-one-seo"

while read dir
do
    # remove directory and create symbolic link to path from file
    rm -rf "$dir" && ln -s "$plugin_dir" "$dir"
done < myfile

    

    

Upvotes: 1

Related Questions