garlock402
garlock402

Reputation: 13

properly using IO redirection to append user input to a file in linux scripting?

I'm just starting to learn linux scripting, and with them user output/inputs. One of the things i need to learn and keep trying to do to no avail is append user input to a file output. Something like

read text > text.dat

or

read text $text > text.dat

Typically ends up in failure, or the creation of text.dat which ends up empty no matter what is typed in by the user. What am i missing?

Upvotes: 1

Views: 2080

Answers (1)

Adam Taylor
Adam Taylor

Reputation: 460

The read command, as documented in it's manual file, will take a line of user input and assign it to a variable which you can name as an argument. It will also split the user input and assign it to multiple variables if you pass more than one name. It will do this all in the background without printing any kind of confirmation to the standard out. We also know that the > operator will redirect the standard out of a command to a file descriptor. It is also important to note that unless bash is explicitly told that a line contains multiple commands (by using a semi-colon or similar) it will assume it is all one command with multiple arguments.

So lets have a look at your examples and see what is happening:

read text > text.dat

This will run the read command, which will silently assign the user input to a variable called $text. It will then redirect the output of the command (nothing, as it is silent) to a file called text.dat. End result: an empty text.dat and an unused $text variable.

read text $text > text.dat

Bash will parse this command and first attempt to get the value assigned to the $text variable, at this point it is undefined and so it will be ignored. So it will run the read command, which will silently assign the user input to a variable called $text. It will then redirect the output of the command (nothing, as it is silent) to a file called text.dat. End result: an empty text.dat and an unused $text variable.

So how can we resolve this? The first command is fine, we use read text to allow the user to input a line and have that line assigned to a variable called $text. Then, we need a way to send that variable to standard out so we can redirect it. To do that, we can use the echo command, which we can redirect.

So for example:

read text
echo $text > text.dat

Another thing to note is that the > operator will overwrite the file, to append to it you can use the >> operator.

So to take a user input and append it to a file we have:

read text
echo $text >> text.dat

Upvotes: 1

Related Questions