Open and write data to text file using Bash?
How can I write data to a text file automatically by shell scripting in Linux? I was able to open the file. However, I don’t know how to write data to it.
12 Answers 12
echo "some data for the file" >> fileName
However, echo doesn’t deal with end of line characters (EOFs) in an ideal way. So, if you’re going to append more than one line, do it with printf :
printf "some data for the file\nAnd a new line" >> fileName
The >> and > operators are very useful for redirecting output of commands, they work with multiple other bash commands.
the operator > redirects output to a file overwriting the file if one exists. The >> will append to an existing file.
If you need to do this with root privileges, do it this way: sudo sh -c ‘echo «some data for the file» >> fileName’
#!/bin/sh FILE="/path/to/file" /bin/cat $FILE text1 text2 # This comment will be inside of the file. The keyword EOM can be any text, but it must start the line and be alone. EOM # This will be also inside of the file, see the space in front of EOM. EOM # No comments and spaces around here, or it will not work. text4 EOM
Newbies would benefit from knowing exactly what to do with this file. How to save it, how to run it, etc.
Please explain rather than simply putting up a piece of code. It would make it so much more helpful to everyone — especially newbies.
You can redirect the output of a command to a file:
If you want to write directly the command is echo ‘text’
If you need root permission: sudo sh -c ‘cat file > /etc/init/gunicorn.conf’ (thanks to lukaserat’s comment above)
An explanation of your code would go a long way toward making it more usable to others. Even callouts of vocabulary like «here document» and «redirection» can point searchers to other resources.
Explanation is never necessary when you already know the answer. To me the above code is not helpful due to lack of details.
I know this is a damn old question, but as the OP is about scripting, and for the fact that google brought me here, opening file descriptors for reading and writing at the same time should also be mentioned.
#!/bin/bash # Open file descriptor (fd) 3 for read/write on a text file. exec 3<> poem.txt # Let's print some text to fd 3 echo "Roses are red" >&3 echo "Violets are blue" >&3 echo "Poems are cute" >&3 echo "And so are you" >&3 # Close fd 3 exec 3>&-
Then cat the file on terminal
$ cat poem.txt Roses are red Violets are blue Poems are cute And so are you
This example causes file poem.txt to be open for reading and writing on file descriptor 3. It also shows that *nix boxes know more fd’s then just stdin, stdout and stderr (fd 0,1,2). It actually holds a lot. Usually the max number of file descriptors the kernel can allocate can be found in /proc/sys/file-max or /proc/sys/fs/file-max but using any fd above 9 is dangerous as it could conflict with fd’s used by the shell internally. So don’t bother and only use fd’s 0-9. If you need more the 9 file descriptors in a bash script you should use a different language anyways 🙂
Anyhow, fd’s can be used in a lot of interesting ways.
Create text file and fill it using bash
I need to create a text file (unless it already exists) and write a new line to the file all using bash. I’m sure it’s simple, but could anyone explain this to me?
9 Answers 9
Creating a text file in unix can be done through a text editor (vim, emacs, gedit, etc). But what you want might be something like this
echo "insert text here" > myfile.txt
That will put the text ‘insert text here’ into a file myfile.txt. To verify that this worked use the command ‘cat’.
If you want to append to a file use this
echo "append this text" >> myfile.txt
If you’re wanting this as a script, the following Bash script should do what you want (plus tell you when the file already exists):
#!/bin/bash if [ -e $1 ]; then echo "File $1 already exists!" else echo >> $1 fi
If you don’t want the «already exists» message, you can use:
#!/bin/bash if [ ! -e $1 ]; then echo >> $1 fi
Save whichever version with a name you like, let’s say «create_file» (quotes mine, you don’t want them in the file name). Then, to make the file executatble, at a command prompt do:
create_file NAME_OF_NEW_FILE
The $1 is a special shell variable which takes the first argument on the command line after the program name; i.e. $1 will pick up NAME_OF_NEW_FILE in the above usage example.
@Switz: See edit explaining $1. If you replace $1 in the script with «text.txt», it will always use «text.txt» as the filename.
Assuming you mean UNIX shell commands, just run
echo prints a newline, and the >> tells the shell to append that newline to the file, creating if it doesn’t already exist.
In order to properly answer the question, though, I’d need to know what you would want to happen if the file already does exist. If you wanted to replace its current contents with the newline, for example, you would use
EDIT: and in response to Justin’s comment, if you want to add the newline only if the file didn’t already exist, you can do
test -e file.txt || echo > file.txt
At least that works in Bash, I’m not sure if it also does in other shells.
How to open a text file from terminal? [closed]
Questions describing a problem that can’t be reproduced and seemingly went away on its own (or went away when a typo was fixed) are off-topic as they are unlikely to help future readers.
I am new to linux and I have a quick question for opening text files using my terminal. I tried many times to open a text file using commands such as
# Option “-x” is deprecated and might be removed in a later version of gnome-terminal.# # Use “-- ” to terminate the options and put the command line to execute after it.# -- xdg-open Random_File.sh --: command not found
I thought that I might have permission issue, but all read, write and execute permissions are available for my text document
Welcome to unix stack exchange. I suggest you look into the following commands: cat , nano , vi , and vim
@ArmenMkrtumyan please refer to my above comment as any one of those commands is capable of opening a .sh file, if you want to edit however then cat won’t help you
Random.sh is not a shell script file. Linux does not use extensions to determine file types. It is a text file, possibly containing assorted shell commands. Might be executable, might be empty, but xdg-open should open it as a text file. Unless, of course, you have managed to create a association to execute it.
since you have worked out the solution with my comment I have turned it into a more flushed out answer for other users benefit. If you are satisfied with it please consider accepting it
4 Answers 4
There are a few solutions:
vi and vim are text editors, anything you can do in vi can be done in vim but both have a big learning curve for beginners. Nano is also a text editor but is much more user friendly than the former (disclaimer: personal opinion), this being said it may not be installed on your system by default. Lastly cat just displays the contents of your file to the command line, so you may not edit with this command.
If the goal is to read a text file from the command prompt, and be able to scroll the text, then most *NIX systems have the utilities less or more that can be used
robert@pip2:/tmp$ less exampleText.txt
If you just want to spew the text to the command line, then try cat
robert@pip2:/tmp$ cat exampleText.txt
If you want to edit a file, then almost all *NIX systems will have vi available
robert@pip2:/tmp$ vi exampleText.txt
You might have some misconfiguration. My comment above about extensions is incomplete. Linux does have a system based on analysing the first few bytes of a file («magic» numbers) because many well-defined formats (executable binary, compressed files, database tables) conform to standards.
However, some tools (launch menus, and xdg-open included) use additional hints to identify specific file types.
The «file» command says this about the files in my home directory:
Paul--) file * > file.txt Box: Bourne-Again shell script, ASCII text executable D_Recovery: directory Executor_1.txt: UTF-8 Unicode text foo.txt: ASCII text, with escape sequences mbox: ASCII text myEnv: ASCII text One: ASCII text One Two Three: ASCII text Pictures: directory Primes: Bourne-Again shell script, ASCII text executable SqlAwk_ENWL.log: ASCII text SqlAwk_NG.log: ASCII text Templates: directory Three: ASCII text Two: ASCII text UL_hSort.txt: ASCII text wdog: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/l, for GNU/Linux 2.6.32, BuildID[sha1]=9a15a7ca3bb94aed54a7a14fb9a11a2dd87d8baa, not stripped wdog.c: C source, ASCII text Xfers: broken symbolic link to /media/paul/0C6E70246E7008AA/Users/Paul/Downloads
When I run xdg-open UL_hSort.txt , the command prompt comes straight back, but it launches an independent GUI for an editor called Xed. It has a tab for the file, and if I hover over that it says it has a Mime type of plain text document with UTF-8 encoding.
I can run xdg-open with other files from the list, and it opens them as additional tabs in the same GUI. It even changes their Mime type, and does syntax colouring, if I save or reload the file. If I open a Jpeg, it launches a GUI for Xviewer for that file instead. If I open a .docx file (MS Word), it opens LibreOffice Writer for it. And so on.