Avoiding overwriting files when redirecting
Setting -o noclobber prevents
writing on existing files.
$ set -o noclobber # (safeguard / turns ON)
$ set +o noclobber # (default / turns OFF)
Setting -o noclobber prevents
writing on existing files.
$ set -o noclobber # (safeguard / turns ON)
$ set +o noclobber # (default / turns OFF)
command > filepath
Redirect stdout of command to filepath
Using the special file /dev/null equivalent discarding.
Using any /tmp/filename makes a temporary buffer that
will be cleared after a few days.
command < filepath
Redirect filepath to stdin for command
Using the special file /dev/urandom equivalent random generator.
/dev/random also, but on older Linux kernels (< 5.6)
it blocks when it runs out of entropy, halting process execution.
command << EOF-c)
python3 -B <<EOF
from pathlib import Path
from itertools import groupby
def walk(d):
if (_ := d.name[:1]) and _ in "._": return
for _ in sorted(d.iterdir()):
if _.is_file(): yield _
if _.is_dir(): yield from walk(_)
k = dict(key=Path.suffix.fget)
groups = groupby(sorted(walk(Path()), **k), **k)
print(*('%-32s %.8i' % (s, L) for s, g in groups
if (L := len([*g])) < 100), sep='\n')
EOF
command <<< string
# Equivalent
sed 's in out ' <<< "stream input"
echo "stream input" | sed 's in out '
# Equivalent
read var <<< "some words"
var="some words"
cmdinto < <(cmdfrom)grep -ozP '(?s)(?<=<style>)(.*?)(?=</style>)'\ < <(curl -s "https://www.wikipedia.org")Piping would be equivalent but would make having to change the URL a few times annoying.
-o only matches-P Perl-regex for lookarounds-z single string input(?s) dot-all modecommand 1>&2Redirect stdout to stderr,
e.g. for error messages: echo "oops" >&2.
command > filepath 2>&1Redirect stderr to where stdout points,
here both into filepath.
Order matters: 2>&1 > filepath
sends stderr to the terminal instead.
command >> filepathLike single > but appends at the end of the file, instead of replacing.
2> 3>, etc.Redirects the file descriptor N. Same applies for other operators.
cmdfrom | cmdintostdout of cmdfrom
to stdin for cmdinto
cmdinto <(cmdfrom)
Process substitution: <(cmdfrom)
becomes a file name like /dev/fd/63,
for commands that take file arguments,
e.g. diff <(ls a) <(ls b).
No space after <.
cmdpre & cmdpost
Starts cmdpre in the background,
then runs cmdpost without waiting.
cmdpre ; cmdpost
Executes cmdpre and then cmdpost
cmdpre && cmdpost
Executes cmdpre, then cmdpost only if
cmdpre returned a zero exit code, i.e. succeeded.
cmdpre || cmdpost
Executes cmdpre, then cmdpost only if
cmdpre returned a non-zero exit code.
Frequently this is equivalent to "failure",
but some commands like grep
return non-zero exit codes in ambiguous scenarios
(1 for no match, 2 for an actual error).
<&- >&-
2>&- [n]>&-.
Closes file descriptor. Respectively stdin, stdout, stderr, file descriptor N.