Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing a file in bash script

Tags:

bash

unix

I a new to bash but I am trying to write a bash script which does the following:

write_to_file()
{
 #check if file exists
 # if not create the file
 # else open the file to edit
 # go in a while loop
 # ask input from user 
 # write to the end of the file
 # until user types  ":q"

 }

If anyone can point out the literature, I would be very thankful Thanks

like image 850
frazman Avatar asked Jan 31 '13 23:01

frazman


People also ask

How do I write to a text file in Linux?

In Linux, to write text to a file, use the > and >> redirection operators or the tee command.

How do you write to a file in Unix?

If you're using a window manager, you can usually press Ctrl + Alt + T to open a new terminal window. If not, log into the system on which you want to create a file through the console. Type cat > newfilename and press ↵ Enter . Replace newfilename with whatever you'd like to call your new file.

How do I save a file in Bash?

In the bash to save the code press esc after esc press the con+x and the alert of do you want to save will appear press "y" over there and hit the enter button. May this help you..


1 Answers

Update: As it's a bash question, you should try this first. ;)

cat <<':q' >> test.file

To understand what is going on, read about bash's IO redirection, heredoc syntax and the cat command


As you see above, there are many ways to do it. To explain some more bash commands I've prepared the function also in the way you've requested it:

#!/bin/bash

write_to_file()
{

     # initialize a local var
     local file="test.file"

     # check if file exists. this is not required as echo >> would 
     # would create it any way. but for this example I've added it for you
     # -f checks if a file exists. The ! operator negates the result
     if [ ! -f "$file" ] ; then
         # if not create the file
         touch "$file"
     fi

     # "open the file to edit" ... not required. echo will do

     # go in a while loop
     while true ; do
        # ask input from user. read will store the 
        # line buffered user input in the var $user_input
        # line buffered means that read returns if the user
        # presses return
        read user_input

        # until user types  ":q" ... using the == operator
        if [ "$user_input" = ":q" ] ; then
            return # return from function
        fi

        # write to the end of the file. if the file 
        # not already exists it will be created
        echo "$user_input" >> "$file"
     done
 }

# execute it
write_to_file
like image 117
hek2mgl Avatar answered Oct 12 '22 11:10

hek2mgl