How can I print the contents of a variable into a text file? For example, I have the following script:

#My Bash
echo "saisir votre nom" 
read $name

I would like to print the contents of $name into a text file. How can I do this?

  • Read? I'm afraid it's not entirely clear what you're asking here... – Mark Williams Mar 18 '15 at 9:26
  • the problem is how can i recover data entered by the user in a text file with bash script how can i do? – Ahmed Znouda Mar 18 '15 at 10:04
  • Please give us example. I don't understand what you want. What do you mean by saying "recover"? – c0rp Mar 18 '15 at 10:18
  • when the user entered data, I want these data will be stored in a text file. Expl: echo (" write your name please") i want that the name while be stored in a text file – Ahmed Znouda Mar 18 '15 at 10:24
  • 2
    @user300458 simple scripting questions are on topic here. – terdon Mar 18 '15 at 11:27

You can just use echo or printf to print the variable and redirect to a file:

read -p "saisir votre nom: "  name
printf "%s\n" "$name" > file.txt

Alternatively, just print it and run the script redirecting its output:

read -p "saisir votre nom: "  name
printf "%s\n" "$name" 


myscript.sh > file.txt

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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