How to record user input to a file in a shell script? [closed]

My friend was showing me a program in shell script where he made where he would open the program, it would ask a question, he would type an answer. Then it would close but whatever he typed as the answer would be transferred to a text document.

5

3 Answers

I'd suggest starting with something like

#!/bin/bash
read -p "Your question here: "
echo "$REPLY" > somefile

You can read more about bash's read command either from the manual page (man bash) or by typing help read at the shell prompt.

If the response doesn't need to be tested , it is sufficient to do it in just one line:

$ echo "Enter blah" && cat > output.txt
Enter blah
blah
# Press Ctrl+D to stop recording stuff into file
$ cat output.txt
blah

What happens here is we use echo to output text on screen. && simply is boolean operator and means "if previous command was successful, execute second one". && is not important here, and ; could be used just as well. cat > output.txt is the fun part - with no file specified, cat will read stdin stream by default ( which in this case is your keyboard ) and parrot it out to stdout. What > does is send stdout stream to file. So basically, we've rewired data streams to go from keyboard to file, instead of keyboard to terminal screen , in just a few characters of text.

This doesn't necessarily need to be done in shell alone, it can be done with other tools, like python:

$ python -c 'import sys;print("Say hello");f=open("output.txt","w");[f.write(l) for l in sys.stdin.readlines()];f.close()'
Say hello
Hello AskUbuntu
# press Ctrl+D
$ cat output.txt
Hello AskUbuntu
#/bin/bash
#Here you can ask your question just edit "Your Question".
echo "Your Question"
#"read" this command reads input from user and store in text what ever
#like word "answer" used here as example.
read answer
#"$answer" this input was taken by user from "read" and stored in word answer . echo prints all words stored in $answer to file like anything.txt or any extention you can use.
echo $answer > any_file.txt
0

You Might Also Like