Bash Noob
Bash Noob

Reputation: 53

Bash Script to copy contents from one file to another

I am trying to create a script where it takes even number of file names, and copy contents from one file to another. for eg: if 4 file names are provided then content of 1 gets copied to file 2 and content of file 3 gets copied to file 4.

until now I could only think of..

if [ expr $# % 2 -ne 0 ]
then
echo: Please enter even number of filenames
exit
fi
for file in $*
do
.....
....

Please advise me how to proceed with this script..Thanks a lot in advance..

Upvotes: 0

Views: 2971

Answers (1)

chepner
chepner

Reputation: 532538

You can remove files from the argument list as you use them, with the shift command:

if (( $# % 2 )); then
    echo Please enter an even number of filenames
    exit 1
fi

while (( $# )); do
    src=$1
    dst=$2
    cp "$src" "$dst"
    shift 2
done

Upvotes: 5

Related Questions