The "read" command, which is built into bash, takes words from the standard input. However, "read" is not good at taking file names if the file names contain spaces. I would like my bash script to ask the user to enter file names, which may contain spaces. Can you think about any technique for this situation?
Suppose that the current directory has the following two files. Each file name contains a space.
Summer View.txt
Winter View.txt
Upon receiving these two file names, the "read" command misinterprets as if there were four files.
read -p "Enter files: "
for i in $REPLY ; do
echo $i
done
-----
Summer\ View.txt Winter\ View.txt
When the above line was passed to "read",
the following output was returned.
Summer
View.txt
Winter
View.txt
-----
"Summer View.txt" "Winter View.txt"
When the above line was passed to "read",
the following output was returned.
"Summer
View.txt"
"Winter
View.txt"
I also tried single quotes, which ended up with the same erroneous output as double quotes.
-----
Is there any solution that will correctly interpret the above kinds of inputs as two files?
The delimiter can be changed from space to other characters by setting $IFS. However, I would rather stick on space for delimiter, because all characters including all symbols seem to be legal for file names or path names on modern GUI OS's.
If these file names are arguments to a script, then they would be correctly interpreted as two files. Consider the following script whose name is MyScript.
for arg ; do
echo $arg
done
MyScript Summer\ View.txt Winter\ View.txt
and
MyScript "Summer View.txt" "Winter View.txt"
correctly output the following two file names.
Summer View.txt
Winter View.txt
However, I need user interaction. I want the user to pass file names in the middle of a script. Please show me a solution that correctly interprets file names when the user passes file names containing spaces upon the prompt by the script.
Thanks a lot, in advance.
Update:
To reflect the feedbacks from posts #2-#6, let me add the following.
I am not interested in any suggestions that attempt to change the delimiter or IFS, even if the change is temporary.
The real problem here is that the "read" command does not understand quotes and backslashes as the shell does. What the "read" command has obtained needs to be re-parsed by correctly handling quotes and backslashes like the shell. Can you think about any technique for such re-parsing?
Perhaps, is there any other command that reads the input from the user and that parses quotes and backslashes as the shell does?
Thanks a lot, in advance.