5

I need to create an empty file using a shell script. The filename will be determined by examining all the files in a directory matching a pattern, say TEST.*, and appending _END to it so that the new file might look like TEST.2011_END. Let the current directory be $DIR. So I tried:

for file in $DIR/TEST.*
do
    touch $file_END  
done

This gives an error. I also tried replacing touch $file_END with:

filename=$file_END  
touch $filename  

but with no luck. What should I do?

2 Answers2

11

The syntax would be:

filename="${file}_END"

or in your code

touch "${file}_END"

The " quotes are not necessary as long as $file does not have any whitespace or globbing character in it.

Mat
  • 52,586
  • 3
    Always put double quotes around variable substitutions unless you know you need field splitting and pathname expansion. This is a simpler and safer approach than trying to figure out whether they are strictly necessary. – Gilles 'SO- stop being evil' Apr 01 '11 at 21:21
2

the command interpreter thinks you mean $file_END ( value of the variable named file_END ). you can work around this by quoting. The syntax could be:

filename="$file""_END"

or

filename="$file"_END

or even

filename=$file"_END"

though i prefer the first one for clarity!

user6218
  • 121