I did some havoc on my computer, when I played with the commands suggested by vezult [1]. I expected the one-liner to ask file-names to be removed. However, it immediately removed my files in a folder:
> find ./ -type f | while read x; do rm '$x'; done
I expected it to wait for my typing of stdin:s [2]. I cannot understand its action. How does the read command work, and where do you use it?
Charlie Martin gives you a good dissection and explanation of what went wrong with your specific example, but doesn’t address the general question of:
When should you use the read command?
The answer to that is – when you want to read successive lines from some file (quite possibly the standard output of some previous sequence of commands in a pipeline), possibly splitting the lines into several separate variables. The splitting is done using the current value of ‘
$IFS‘, which normally means on blanks and tabs (newlines don’t count in this context; they separate lines). If there are multiple variables in the read command, then the first word goes into the first variable, the second into the second, …, and the residue of the line into the last variable. If there’s only one variable, the whole line goes into that variable.There are many uses. This is one of the simpler scripts I have that uses the split option:
The
catcommand with a here-document has its output sent to a pipe, so the output goes into thewhile read dbs loggingloop. The first word goes into$dbsand is the name of the (Informix) database I want to create. The remainder of the line is placed into $logging. The body of the loop deals with unlogged databases (wherebeginandcommitdo not work), then run a programsqlcmd(completely separate from the Microsoft new-comer of the same name; it’s been around since about 1990) to create a database and populate it with some standard tables and data – a simulation of the Oracle ‘dual‘ table, and a set of tables related to the ‘table of elements’.Other scripts that use the
readcommand are bigger (by far), but generally read lines containing one or more file names and some other attributes of relevance, and then apply an appropriate transform to the files using the attributes.‘Osiris JL: ‘ is my command line prompt; I ran this in my ‘bin’ directory. ‘
wgrep‘ is a variant of grep that only matches entire words (to avoid words like ‘already’). This gives some indication of how I’ve used it.The ‘
read x || exit‘ lines are for an interactive script that reads a response from standard input, but exits if the command gets EOF (for example, if standard input comes from/dev/null).