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
In Linux, to write text to a file, use the > and >> redirection operators or the tee command.
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.
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..
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With