How to create a file with content in Bash?

Member

by sincere , in category: Other , 2 years ago

How to create a file with content in Bash?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@sincere You can use echo and > to create a file with custom content in Bash, here is shell script as example:


1
2
3
#!/bin/sh

echo 'Lorem ipsum dolor.' > file.txt


Member

by violette , a year ago

@sincere 

In Bash, you can create a file and add content to it using the echo command and redirecting the output to a file. For example, to create a file called "example.txt" with the content "Hello, World!" you would use the following command:

1
echo "Hello, World!" > example.txt


You can also use the echo command to append content to an existing file using the >> operator. For example, to add the content "This is an example." to the "example.txt" file you would use the following command:

1
echo "This is an example." >> example.txt


Alternatively you can use cat command to write content to a file or create a file and write content at the same time. For example,

1
2
3
cat > example.txt << EOL
Hello, World!
EOL


It's important to note that the above commands will overwrite the file if the file already exists with the same name. To avoid overwriting the file you can use > operator to create a new file with different name or use nano or vi command to open the file in the editor and write the content.