Skip to content

Instantly share code, notes, and snippets.

@karakays
Last active June 1, 2021 20:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karakays/d4434181dd787d04d196f326e6f0ba46 to your computer and use it in GitHub Desktop.
Save karakays/d4434181dd787d04d196f326e6f0ba46 to your computer and use it in GitHub Desktop.

My favorite GNU coreutils/bash commands

ls

  • follow symlinks (file or directory)
    ls -L winhome/

tr

  • translate, delete or squeeze characters
    tr [char1] [char2]

  • from stdin by default
    echo file | tr "\r" "\r\n"b

  • Remove \r in file
    tr -d $'\r' < file

  • squeeze repeats in file
    tr -s a < file

grep

  • Grep foo as a basic regex pattern recursively
    grep -R foo dir/

  • Grep foo as a string literal
    grep -RF foo dir/

  • Grep as Perl regex
    grep -RP 'foo\w+' dir/

  • Give a bit context around
    grep -C 3 WARN *.log

  • Grep only in xml
    grep -R --include=*.xml foo dir/

  • Output file names only instead of results
    grep -l foo dir/

find

  • Find name under root
    find / -iname "name*"

  • Find and exec cmd for each file. semicolon is necessary to distinguish it from find args. Escape semicolon from bash. Escape {} from bash.
    find / -iname name -exec cmd '{}' \;

  • Find and exec cmd once for all files.
    find / -iname name -exec cmd '{}' \+

sed

  • substitute in-place first match only per line (default)
    sed -i 's/foo/bar/' file

  • backup and substitute in-place
    sed -i.bak 's/foo/bar/' file

  • backup and substitute in-place globally
    sed -i 's/foo/bar/g' file

  • find and subsitute returns
    find bundle/ -iname "*.vim" -exec sed -i 's/\r//' '{}' \;

cp

  • Copy tree without root
    cp -a source/. dest/
  • Copy tree with root
    cp -a source dest/ local registry

top

  • Switch total memory unit E
  • Switch memory unit by process e

man

lsof

eval

Concatenate args and execute it in the current shell environment.

eval "$(pyenv init -)"

Bash scripts run in a forked process, anything it does directly to environment variables is lost when it exits.

It is equivalent to put command output into a temporary file and source it.

pyenv init - > tmp && source tmp

source

Runs commands within the running shell's process.

# script
export FOO=BAR

./script

script is run in a sub-shell and any environment variable defined in it is lost after execution. To retain them

source script

https://tldp.org/LDP/abs/html/subshells.html

dd

Read and write raw bytes in blocks.

Read 1K random bytes and print to stdout

dd if=/dev/urandom bs=1024 count=1

Read 128 random bytes and encode it

dd if=/dev/urandom bs=128 count=1 | base64

| vs. <<<

echo "cello world" | read first second

vs.

read first second << "cello world"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment