Bash by Example: Create File
Different ways to create new files including the touch command for empty files, output redirection operators for files with content, and the dd utility for binary files with specific sizes, understanding file creation permissions and umask, implementing atomic file creation patterns, and choosing the appropriate method based on file type and content requirements.
Code
#!/bin/bash
# 1. Using touch (updates timestamp or creates empty file)
touch newfile.txt
echo "Created newfile.txt"
# 2. Using redirection (creates empty file or truncates)
> empty.log
echo "Created empty.log"
# 3. Writing content immediately
echo "Hello World" > content.txt
echo "Created content.txt"
# 4. Creating large file with dd (e.g., 1MB)
dd if=/dev/zero of=largefile.dat bs=1M count=1 status=none
echo "Created largefile.dat"
# Cleanup
rm newfile.txt empty.log content.txt largefile.datExplanation
Creating files is a fundamental task. The touch command is the standard way to create an empty file if it doesn't exist, or update its modification time if it does. It is safe because it doesn't overwrite existing content.
Shell redirection > is another common method. Using > filename (with no command before it) creates an empty file. Warning: If the file already exists, this will truncate it (delete all content) to zero bytes immediately.
For creating files with specific content or sizes, you can redirect the output of commands like echo, cat, or dd.
Code Breakdown
touch is the most common command for this. It ensures the file exists without modifying content if it's already there.> file. This is a shorthand to truncate or create a file. Equivalent to : > file.dd is a low-level utility. Here it copies 1 block of 1 Megabyte from /dev/zero (infinite null bytes) to the file.
