|
Shell provides several ways to write data to files using redirection operators. This example covers common file writing patterns. Basic write with |
|
|
Output:
Created file with: Hello, World! |
|
|
Append with >> (adds to end of file): |
|
|
Output:
Appended file: First line Second line Third line |
|
|
Write multiple lines with here-document: |
|
|
Output:
Here-document file: This is line 1 This is line 2 This is line 3 |
|
|
Here-document with variable expansion: |
|
|
Output:
Template with variables: Hello, Alice! Today is Wed Jan 1 10:00:00 UTC 2025 Your home is /root |
|
|
Write without newline using printf: |
|
|
Output:
No newline here - continued |
|
|
Redirect stdout and stderr: |
|
|
Output:
Redirect stdout (1) and stderr (2): Stderr captured: ls: cannot access '/nonexistent': No such file or directory |
|
|
Discard output: |
|
|
Output:
Discarding output: Stderr discarded (no error shown) |
|
|
Tee - write to file and stdout simultaneously: |
|
|
Output:
Using tee: This goes to both File contains: This goes to both Append with tee -a: This goes to both Appended line |
|
|
Write from pipeline: |
|
|
Output:
Pipeline to file: 1 2 4 5 |
|
|
Atomic write (write to temp, then rename): |
|
|
Output:
Atomic write result: Important data |
|
|
Write with file descriptor: |
|
|
Output:
File descriptor write: Line 1 Line 2 |
|
|
Append with file descriptor: |
|
|
Output:
Appended line |
|
|
Create file if not exists, don’t overwrite: |
|
|
Output:
Safe write (no overwrite): New content |
|
|
Truncate file to empty: |
|
|
Output:
After truncate, size: 0 bytes |
|
|
Bash
Bash provides noclobber option to prevent overwriting: |
|
|
Write to multiple files at once: |
|
|
Output:
File1: Multiple files File2: Multiple files |
|
|
Write binary data: |
|
|
Output:
Binary write: Hello |
|
|
Write with specific permissions: |
|
|
Output:
Permissions: -rw------- |
|