Skip to content

Tips: Shell ​

All kinds of arrows ​

  • File descriptor 0 is stdin (/dev/stdin)
  • File descriptor 1 is stdout (/dev/stdout)
  • File descriptor 2 is stderr (/dev/stderr)
1>   >  Redirect stdout to a file, write
1>>  >> Redirect stdout to a file, append

2>      Redirect stderr to a file, write
2>>     Redirect stderr to a file, append

&>      Redirect both to a file, write
&>>     Redirect both to a file, append

1>&2    Copy stderr to stdin
2>&1    Copy stdin to stderr
<       Use file as stdin
<<      here-document
<<<     here-string
<(xxx)  process substitution

<< here-document ​

sh
cat <<EOF
This is a here-document example.
You can write multiple lines of text.
EOF

<<< here-string ​

sh
grep "example" <<< "This is an example of a here-string."

<(...) process substitution ​

The command inside of the "<(...)" get executed first. It's output is saved to a temporary file. And that file path will replace the entire "<(...)".

sh
diff <(echo "File A content") <(echo "File B content")

alternative ways to write to a file ​

This is the default way:

sh
... > out.txt

You can also do this. This is useful over ssh connection or when writing to the output file requires sudo.

sh
... | cat > out.txt
... | tee out.txt > /dev/null

shell flags ​

set -x     print each line before execute
set +x     disable it

set -e     exit when any command fails
set +e     disable it

man sections ​

What do the numbers in a man page mean? - Unix & Linux Stack Exchange

Run man man to find out.


console
$ man man
MANUAL SECTIONS
    The standard sections of the manual include:

    1      User Commands
    2      System Calls
    3      C Library Functions
    4      Devices and Special Files
    5      File Formats and Conventions
    6      Games et. al.
    7      Miscellanea
    8      System Administration tools and Daemons

    Distributions customize the manual section to their specifics,
    which often include additional sections.
console
$ man 1 printf
$ man 3 printf
$ man -a printf

record shell session with scriptreplay ​

record and replay everything happening in your terminal, with this linux utility tool.


script and scriptreplay ​

record and replay everything happening in your terminal, with this linux utility tool.

$ man script
     The script utility makes a typescript of everything printed on your terminal.  It is useful
     for students who need a hardcopy record of an interactive session as proof of an assignment,
     as the typescript file can be printed out later with lpr(1).

macOS might require: brew install util-linux

To use:

script -a "$(date -Is)".log -t"$(date -Is)".time

scriptreplay -t=xxx.time xxx.log

snippet: generate random chars ​

# All base 64 characters
cat /dev/urandom | base64 | head -c 10


# Alphanumerics only
cat /dev/urandom | base64 | tr -cd "[:upper:][:lower:][:digit:]" | head -c 16

Created on 2021-01-17

Last updated on 2025-04-15