Copying files using $filename

Hi,
I've a problem. Here is the code:

#!/bin/ksh
echo "enter a file name"
read a
cd /home/linux1/sam
if [ -e $a ]
then
echo "file exists"
cp $a $a_bkp
else
echo "file doesn't exist"
fi

when executed the o/p is:

enter a file name
contact
file exists
cp: missing destination file
Try `cp --help' for more information.

The copy command using $a is not working. Could anybody please guide in this regard?

make your code look like the following and it will work for you. You need to put "" around the the second "$a"_bkp. You might also want to do a cp -p to preserve ownership, permissions, etc.

#!/bin/ksh

dir=/home/linux1/sam

echo "enter a file name"
read a
cd $dir
if [ -e $a ]
then
echo "file exists"
cp -p $a $dir/"$a"_bkp
else
echo "file doesn't exist"
fi
1 Like

to make it more clear

cp $a $a_bkp

You dont have the $a_bkp variable -- do proper quoting according to your shell so that you get the $a value, and concatenate it with _bkp.

Thanks linuxn00b. Itz working. And thanks to thegeek for the suggestion

To customize ..

$ read a; [ -e "$a" ] && echo "File exists" && cp $a ${a}_bkp || echo "File not exists"