Create a text file and fill it with bash

I need to create a text file (if it does not already exist) and write a new line to the file using bash.

I'm sure this is simple, but can anyone explain this to me?

+43
unix
Jan 11 2018-11-11T00:
source share
4 answers

If you want it to be like a script, the following Bash script should do what you need (plus indicate when the file already exists):

#!/bin/bash if [ -e $1 ]; then echo "File $1 already exists!" else echo >> $1 fi 

If you do not need the message "already exists", you can use:

 #!/bin/bash if [ ! -e $1 ]; then echo >> $1 fi 

Change usage:

Save any version with a name that you like, say "create_file" (mine quotes, you don’t want them in the file name). Then, to make the executatble file, at the command prompt, run:

 chmod u+x create_file 

Put the file in a directory in your path , and then use it with:

 create_file NAME_OF_NEW_FILE 

$ 1 is a special shell variable that takes the first argument on the command line after the program name; those. $ 1 will receive NAME_OF_NEW_FILE in the above use case.

+17
Jan 11 2018-11-11T00:
source share
β€” -

Creating a text file in unix can be done using a text editor (vim, emacs, gedit, etc.). But what you want may be something like this

 echo "insert text here" > myfile.txt 

This will put the text "paste text here" in the myfile.txt file. To make sure this works, use the "cat" command.

 cat myfile.txt 

If you want to add to the file, use

 echo "append this text" >> myfile.txt 
+39
Jan 11 2018-11-11T00:
source share

Assuming you mean UNIX shell commands, just run

 echo >> file.txt 

echo prints a new line, and >> tells the shell to add this line to the file, creating if it does not already exist.

To correctly answer the question, I needed to know what you want if the file already exists. If you want to replace its current contents with a new line, for example, you would use

 echo > file.txt 

EDIT: and in response to Justin's comment, if you want to add a new line only if the file does not exist yet, you can do

 test -e file.txt || echo > file.txt 

At least this works in Bash, I'm not sure if it also works in other shells.

+10
Jan 11 2018-11-11T00:
source share

Your question is a bit vague. This is a shell command that does what I think you want to do:

 echo >> name_of_file 
+2
Jan 11 '11 at 21:40
source share



All Articles