Reading and Writing#
Beyond listing files, the operator’s everyday I/O is putting data in and getting data out. The same set of commands covers tiny configs, terabyte logs, and binary blobs because Linux treats all of them as byte streams against a path.
Reading#
Form |
Effect |
|---|---|
|
print contents |
|
pager |
|
first / last N lines |
|
follow as the file grows |
|
read a single line into a shell variable |
|
read all lines into a Bash array |
|
safe line loop |
Writing (redirections)#
Form |
Effect |
|---|---|
|
write stdout, truncating |
|
append stdout |
|
write stderr, truncating |
|
append stderr |
|
stdout + stderr → file |
|
same (Bash short form) |
|
discard everything |
|
write and keep going on stdout |
|
append + tee |
|
feed file as stdin |
|
here-string as stdin |
|
truncate FILE to zero bytes |
Heredocs#
$ cat <<EOF > /etc/myapp/config.yml
$ server:
$ port: 8080
$ host: $HOSTNAME
$ EOF
$ cat <<'EOF' > script.sh
$ echo $LITERAL
$ EOF
$ tr a-z A-Z <<-EOF
$ hello
$ world
$ EOF
Writing without a process#
Form |
Effect |
|---|---|
|
simple write |
|
safer for arbitrary data |
|
create or empty a file in one syscall |
Process substitution#
Form |
Effect |
|---|---|
|
treat command output as files |
|
send streams through filters |
Atomic writes#
A common safe-write pattern. Write to a temp file in the same directory, then rename.
$ cat > "$f.tmp" <<EOF
$ contents
$ EOF
$ mv "$f.tmp" "$f"
mv (rename) within the same filesystem is atomic; readers either
see the old file or the new one, never a half-written one.
Editing in place#
Form |
Effect |
|---|---|
|
in-place substitution (GNU) |
|
BSD / macOS (note empty arg) |
|
portable alternative |
|
POSIX-correct in-place edit |
Splitting and joining#
Form |
Effect |
|---|---|
|
split by line count |
|
split by byte count |
|
reassemble |
Useful tools#
Form |
Effect |
|---|---|
|
raw block copy |
|
CoW copy on Btrfs / XFS / APFS |
|
preserve everything, with progress |
|
overwrite then delete (limited use on CoW / journaled filesystems) |
References#
man 1 cat,man 1 less,man 1 head,man 1 tail,man 1 read,man 1 mapfile(reading file contents).man 1 tee,man 1 echo,man 1 printf,man 1 truncate(writing without a process).man 1 sed,man 1 perl,man 1 ex(in-place editing).man 1 split,man 1 dd,man 1 cp,man 1 rsync,man 1 shred(bulk move and copy).man 1 fallocate,man 1 mv(atomic write pattern).Files for the file-as-byte-stream model these tools build on.
Archives for compressed and bundled forms.
Encryption for sealing the byte stream before it lands on disk.
Standard I/O for the redirection mechanics behind
>,>>,|, and heredocs.