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.
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.