hdub
hdub

Reputation: 321

bash script to copy file into multiple specified directories

I'm looking to create a script that takes a file and copies the file to multiple directories

e.g. cp2dir filename dir1/ dir2/ dir3/

I've dug around and it looks like my route is to use cat <inputfile> | tee <outputfile> <outputfile> <outputfile> however, previous scripts that I have found appear to be using static files/directories.

How do I go about doing this with user input?

I'm thinking:

for i in $dir; do
    cat $file | tee $i

Where $dir and $file are user input. Would I need to cut -d\ $dir?

Upvotes: 0

Views: 642

Answers (2)

John Kugelman
John Kugelman

Reputation: 361605

cp2dir() {
    local file="$1" dir
    shift

    for dir in "$@"; do
        cp "$file" "$dir"
    done
}

Upvotes: 3

kojiro
kojiro

Reputation: 77107

cp2dir() {
    local file="$1"
    shift
    local -a dirs=( "$@" )

    for dir in "${dirs[@]}"; do
        cp "$file" "$dir"
    done
}

Of course, this doesn't do any safety checks, like making sure the targets are actually directories. I leave that to you.

Upvotes: 4

Related Questions