Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
    
touch is often used to create an empty file, but its primary purpose it to touch a file's timestamp... If a file with the name already exist, 'touch' will not make it become "empty".... If you want to force an existing file to be empty (thereby losing any data it contains), you can use cp /dev/null "${file}_END" which will either create an empty file if it doesn't currently exist, or if it does exist, it will truncate it to zero length (ie. empty)... –  Peter.O Apr 1 '11 at 15:42
    
@fred.bear: A common idiom to create or truncate a file is : >"${file}_END" –  Gilles Apr 1 '11 at 21:22
    

2 Answers 2

up vote 7 down vote accepted

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.

share|improve this answer
2  
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 Apr 1 '11 at 21:21

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!

share|improve this answer
1  
I consider "${file}_END" more clear still. –  glenn jackman Apr 1 '11 at 15:01

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.