0

I wrote a bash script:

date=$( date +%F ) 
cp $1 $1_$date

When written this way and provided a single argument, it works fine. But if I write:

cp $1 $date_$1

I get an error message:

cp: ‘1.sh’ and ‘1.sh’ are the same file

Could someone explain to me, please, why it happens and how it can be solved. Thanks!

Nikolay Komolov
  • 125
  • 1
  • 1
  • 5
  • 2
    cp $1 $date"_$1" works. this way bash knows when one variable name ends and the other starts – amdixon Aug 30 '15 at 06:40
  • 3
    Use ${date} which tells where variable ends – Mahesh Kharvi Aug 30 '15 at 06:53
  • 2
    Not strictly a duplicate (though I'm sure we could find one) but the explanation is in http://stackoverflow.com/questions/8748831/bash-when-do-we-need-curly-braces-in-variables – tripleee Aug 30 '15 at 06:53

1 Answers1

3

The problem is that _ is a perfectly valid character in a variable name.

Rewrite like this:

cp $1 ${date}_$1

What's happening is the value of $date_ (notice the trailing _), is probably empty. So your command becomes really cp $1 $1. By using the braces, we clarify that the name of the variable is "date" and not "date_".

You should also quote variables used is filenames, in case they contain spaces:

cp "$1" "${date}_$1"
janos
  • 120,954
  • 29
  • 226
  • 236