Creating Files

You're setting up a new project. First thing you need: files.

Let's learn multiple ways to create them, because different situations call for different tools.

touch - Create Empty Files

The simplest way to create a file:

Terminal
$touch newfile.txt
$ls -l newfile.txt
-rw-r--r-- 1 user user 0 Jan 14 10:00 newfile.txt

The file exists but has 0 bytes - it's empty.

Create Multiple Files

Terminal
$touch file1.txt file2.txt file3.txt
$ls
file1.txt file2.txt file3.txt

Or with brace expansion:

Terminal
$touch test{1,2,3}.txt
$ls
test1.txt test2.txt test3.txt

Brace Expansion

{1,2,3} expands to 1 2 3. You can also do {1..10} for ranges. Very powerful for bulk operations.

What touch Really Does

touch has a dual purpose:

  1. Create a new empty file if it doesn't exist
  2. Update the timestamp if it does exist
Terminal
$ls -l file.txt
-rw-r--r-- 1 user user 100 Jan 14 08:00 file.txt
$touch file.txt
$ls -l file.txt
-rw-r--r-- 1 user user 100 Jan 14 10:30 file.txt

The content stays the same, but the modification time updates. This is useful for triggering builds or updating backups.

Create Files with Content

Using echo

Terminal
$echo "Hello World" > greeting.txt
$cat greeting.txt
Hello World

The > redirects output to a file, creating it if needed.

Overwrite Warning

> overwrites the file completely. Use >> to append instead.

Using cat and Here Documents

For multi-line content:

hljs bash
cat > config.txt << EOF
server=localhost
port=3000
debug=true
EOF
Terminal
$cat config.txt
server=localhost port=3000 debug=true

This creates a file with multiple lines in one command.

Using Text Editors

For anything more complex, use a text editor:

hljs bash
nano newfile.txt    # Opens nano editor
vim newfile.txt     # Opens vim editor

We'll cover editors in detail later.

Naming Best Practices

Good file names:

  • project-notes.txt (hyphens)
  • project_notes.txt (underscores)
  • project.notes.txt (dots)

Avoid:

  • project notes.txt (spaces cause headaches)
  • Project Notes.txt (mixed case is asking for trouble)
  • my file (final) v2 FINAL.txt (please don't)

No Spaces

Spaces in filenames work but require quoting or escaping. Save yourself the hassle - use hyphens or underscores.

Create Files in Different Locations

Terminal
$touch /tmp/tempfile.txt
$touch ~/Documents/notes.txt
$echo "log entry" > /var/log/myapp.log
Permission denied (if not root)

You can only create files in directories you have write permission for.

Knowledge Check

What happens if you `touch` a file that already exists?

Key Takeaways

  • touch filename creates empty files
  • touch also updates timestamps on existing files
  • echo "content" > file creates files with content
  • > overwrites, >> appends
  • Avoid spaces in filenames - use hyphens or underscores
  • Use brace expansion for creating multiple files: {1..5}

Next: creating directories with mkdir.