Create and write file in single Linux/macOS command


If you want to create a fine and write to it in a single command you can do it in various ways, one of the way is to use the echo command and use > redirect the text to a file, but doing so the file will be created and echoed text will be written to the file.


Example:
bash $ echo "This will be written to the file" > myFile.txt

bash $ cat myFile.txt
This will be written to the file


Create and wirte a file in one command


You can in this way also redirect the output of a command to a file.

Example:
bash-3.2$ cd /
bash-3.2$ ls > /Users/code2care/Desktop/myFile.txt

bash-3.2$ cat /Users/code2care/Desktop/myFile.txt
Applications
Library
System
Users
Volumes
bin
cores
dev
etc
home
opt
private
sbin
tmp
usr
var

Comments:

  • Thanks!
    03 Jul 2022 17:07:05 GMT
  • Further comments disabled!
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.