It's not the best title, so might I suggest "Trim trailing spaces from file" or such might be better? Can you edit this or do you need a moderator/administrator to?
I have a few to questions pose in response first:-
Is this homework/assignment? There are specific forums for these.
What have you tried so far?
What output/errors do you get?
What OS and version are you using?
What are your preferred tools? (C, shell, perl, awk, etc.)
What logical process have you considered? (to help steer us to follow what you are trying to achieve)
Most importantly, What have you tried so far?
There are probably many ways to achieve most tasks, so giving us an idea of your style and thoughts will help us guide you to an answer most suitable to you so you can adjust it to suit your needs in future.
We're all here to learn and getting the relevant information will help us all.
Per our forum rules, all threads must have a descriptive subject text. For example, do not post questions with subjects like "Help Me!", "Urgent!!" or "Doubt". Post subjects like "Execution Problems with Cron" or "Help with Backup Shell Script".
The reason for this is that nearly 95% of all visitors to this site come here because they are referred by a search engine. In order for future searches on your post (with answers) to work well, the subject field must be something useful and related to the problem!
In addition, current forum users who are kind enough to answer questions should be able to understand the essence of your query at first glance.
So, as a benefit and courtesy to current and future knowledge seekers, please be careful with your subject text. You might receive a forum infraction if you don't pay attention to this.
You have an unquoted variable in a command argument!
The shell does much more with it than removing the trailing spaces. It also removes leading spaces and replaces inter-whitespace by a single space character. And worse, it evaluates glob patterns like * i.e. substitutes them by matching filenames in the current directory.
The latter you can prevent with set -f
(
# a sub shell limits the scope of the following set command
set -f # disable glob expansion in command arguments
while read line
do
printf "%s\n" $line
done < infile > outfile
)
General rule: in command arguments never have an unquoted variable, unless you have full control over its contents!
Note that echo and [ ] are commands!