3

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
  • What shell are you talking about? bash, zch, csh, tcsh, ...? Which version of Ubuntu are you running?
    – Jan
    Sep 6, 2014 at 20:25
  • i am using bash and I am using ubuntu 13.10 Sep 6, 2014 at 20:44
  • This question is most probably better suited for stackoverflow.
    – Jan
    Sep 6, 2014 at 20:45
  • 6
    @Jan Neither Ask Ubuntu nor Stack Overflow are places where "write my code for me" is acceptable as a question, so suggesting they post on Stack Overflow isn't likely to end in a good experience for them.
    – Seth
    Sep 6, 2014 at 23:32
  • @TheWaffleNinja Does the input need to be appended to the end of the file, or a new file created for it? If the latter, should the old file (or its contents) be replaced? While this is answerable (and has been answered) already, it could be made more specific. Sep 7, 2014 at 0:19

3 Answers 3

5

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.

2

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
0
#/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

Not the answer you're looking for? Browse other questions tagged or ask your own question.