Skip to content

Latest commit

 

History

History
615 lines (450 loc) · 22.4 KB

CodeSnippets.md

File metadata and controls

615 lines (450 loc) · 22.4 KB

Code snippets

dotfiles

add

manual

to add dotfiles of the variety Mackup might’ve but hasn’t yet:

# make `~/Desktop/.example.txt` part of the dotfiles repository
add="${HOME%/}"'/Desktop/.example.txt'
command mv -- "${add-}" "${DOTFILES-}"'/directory_where_it_should_go_if_any/'"${add##*/}"
command ln -s -- "${DOTFILES-}"'/directory_where_it_should_go_if_any/'"${add##*/}" "${HOME%/}"'/directory_where_it_should_go_if_any/'"${add##*/}"
unset -v -- add
lists
applications
command find -- \
  /System/Applications \
  /Applications \
  -maxdepth 3 \
  -name '*.app' 2>/dev/null |
  command sed -e 's/.*\/\(.*\)\.app/\1/' |
  LC_ALL='C' command sort -d -f

On Alpine Linux, generate a list of installed packages with:
command apk --verbose --verbose info | LC_ALL='C' command sort # via

Homebrew
command brew list -1
MANPATH
command printf -- '%s\n' "${MANPATH-}" |
  command sed -e 's/:/\n/g'
man pages

Definintions of the numbers that follow man commands (via)

section contents
1 User commands, executable programs, shell commands
2 System calls (functions provided by the kernel)
3 Library calls (C library functions)
4 Special files, devices (like in /dev)
5 File formats, conventions (like /etc/passwd)
6 Games
7 Miscellaneous; conventions like man(7), man-pages(7)
8 System administration tools, daemons (usually for root)
9 Kernel interfaces, routines [non-standard]
pip packages
{ command python -m pip list --format=columns || command python -m pip3 list --format=columns || command python3 -m pip list --format=columns || command python3 -m pip3 list --format=columns; } 2>/dev/null

apk

testing

apk add foo # unavailable? \
# then try \
apk add foo@testing # via

list everything recursively in a directory

with full paths

find -- . # via

and metadata

command find -- . -ls

lines, words, characters

in, for example, a C++ project directory, measuring only .cpp and .hpp files. via

command find -- . '(' -name '*.cpp' -o -name '*.hpp' ')' -exec wc -- {} + |
  LC_ALL='C' command sort -n

search

grep

search for the word “example” inside the current directory which is “.”

command find -- . \
  -type f \
  -exec grep -i -n -e 'example' -- {} +

locate all

for example, locate all JPEG files in the current directory . and below:

command find -- . '(' -name '*.jpg' -o -name '*.JPEG' -o -name '*.JPG' -o -name '*.jpeg' ')' -type f

PATH

command printf -- '%s\n' "${PATH-}" |
  command sed -e 's/:/\n/g'

executables

command printf -- '%s\n' "${PATH-}" | command sed -e 's/:/\n/g' | while IFS='' read -r -- directory; do command find -- "${directory-}" -mindepth 1 -maxdepth 1 ! -type d -exec test -x {} ';' -print 2>/dev/null; done

text editing

export output

printf 'First Name\n' >./ExampleFileWithGivenName.txt # create a text file with “First Name” and a new line
printf 'Other First Name\n' >./ExampleFileWithGivenName.txt # the “>overwrites the existing file
printf 'Last Name\n' >>./ExampleFileWithGivenName.txt # the “>>appends to the existing document

sort

command env >./example.txt # save an unordered list of env variables
command env | LC_ALL='C' command sort >./example.txt # via save the variables in an alphabetically ordered list

EOL and EOF encoding

find (?<![\r\n])$(?![\r\n]) # via
replace \r\n

make invisible

chflags -hvv hidden example.txt
-h for symbolic links, if applicable, but not their targets
-v₁ for verbose
-v₂ for printing the old and new flags in octal to stdout

create an alias

ln -s (link, symbolic) uses arguments just like cp existing new (via):

ln -s existing_file shortcut_to_file

launch services

reset

remove bogus entries from Finder’s “Open With” menu (via)
/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -kill -seed -r -domain local -domain system -domain user && killall Finder

repair site disk permissions

via

command find -- . -path '*/.*' -prune -o -type d -exec chmod -- 755 {} +
command find -- . -path '*/.*' -prune -o -type f -exec chmod -- 644 {} +

date modified modify

touch -t 2003040500 file.txt # date modified → 2020-03-04 5:00am

case-naming conventions

Naming Convention Format
Camel Case camelCase
Camel Snake Case camel_Snake_Case
Capital Case Capital Case
Cobol Case COBOL-CASE
Constant Case CONSTANT_CASE
Dash Case dash-case
Dot Case dot.case
Dromedary Case dromedaryCase
Flat Case flatcase
HTTP Header Case HTTP-Header-Case
Kebab Case kebab-case
Lisp Case lisp-case
Lower Camel Case lowerCamelCase
Lower Case lower case
Macro Case MACRO_CASE
Mixed Case Mixed Case
Pascal Case PascalCase
Pascal Snake Case Pascal_Snake_Case
Pothole Case pothole_case
Screaming Kebab Case SCREAMING-KEBAB-CASE
Screaming Snake SCREAMING_SNAKE_CASE
Sentence case Sentence case
Snake Case snake_case
Spinal Case spinal-case
Studly Case StudlyCase
Title Case Title Case
Train Case Train-Case
Upper Camel Case UpperCamelCase
Upper Case UPPER CASE

C, C++

flags

-Wall -Wextra -pedantic
#ifdef __APPLE__
    -Weverything <!-- do not use (via) -->
#endif
-Woverriding-method-mismatch -Weffc++ -Wcall-to-pure-virtual-from-ctor-dtor -Wmemset-transposed-args -Wreturn-std-move -Wsizeof-pointer-div -Wdefaulted-function-deleted # via
-lstdc++ # via but this might – or might not – be helpful on macOS using gcc or g++

C++ features before wide support

for example, C++17’s <filesystem>
-lstdc++fs

run cpplint recursively

cpplint --verbose=0 --linelength=79 --recursive --extensions=c++,cc,cp,cpp,cxx,h,h++,hh,hp,hpp,hxx .

run cppcheck recursively

cppcheck --force -I "${CPATH-}" .

compile all files of type .𝑥 in a directory

C

via, via

command find -- . -maxdepth 1 -name '*.c' -type f -exec gcc -std=c89 --verbose -save-temps -v -Wall -Wextra -pedantic -- {} +

C++

command find -- . -maxdepth 1 -name '*.cpp' -type f -exec g++ -std=c++2a --verbose -Wall -Wextra -pedantic -save-temps -v -pthread -fgnu-tm -lm -latomic -lstdc++ -- {} +

Clang

command find -- . -maxdepth 1 -name '*.cpp' -type f -exec clang++ -std=c++2a --verbose -Wall -Wextra -pedantic -v -lm -lstdc++ -pthread -save-temps -- {} +

Gatekeeper

do not disable it, because that would allow you to install any software, even if unsigned, even if malicious:
sudo spctl --master-disable # via

Git

git add

via

content to add Git command
modified files only git add --updated or git add -u
everything except deleted files git add .
everything git add --all or git add -A

git diff

more detailed git diff and how I once found an LF‑to‑CRLF‑only difference

git diff --raw

git commit

with subject and body

git commit --message='subject' --message='body' # via

in the past

to backdate a commit:
GIT_TIME='2000-01-02T15:04:05 -0500' GIT_AUTHOR_DATE=$GIT_TIME GIT_COMMITTER_DATE=$GIT_TIME git commit --message='add modifications made at 3:04:05pm EST on January 2, 2000' # via

git config

editor

Vim
git config --global core.editor /usr/local/bin/vim
Visual Studio Code

git config --global core.editor "code --wait"

git tag

git tag v𝑖.𝑗.𝑘 # where 𝑖, 𝑗, and 𝑘 are non-negative integers representing SemVer (semantic versioning) major, minor, and patch releases
git push origin v𝑖.𝑗.𝑘 # push the unannotated tag via

Numbers

Affixes

Definition Prefix Suffix
binary b𝑛 𝑛
octal o𝑛 𝑛
decimal d𝑛 𝑛₁₀
hexadecimal x𝑛 𝑛₁₆

Operating system

Identify

printf '\n\140uname -a\140:\n%s\n\n' "$(uname -a)"; \
command -v -- sw_vers >/dev/null 2>&1 && # via \
printf '\n\140sw_vers\140:\n%s\n\n' "$(sw_vers)"; \
command -v -- lsb_release >/dev/null 2>&1 && # via \
printf '\n\140lsb_release --all\140:\n%s\n\n' "$(lsb_release --all)"; \
[ -r /etc/os-release ] && # via \
printf '\140cat /etc/os-release\140:\n%s\n\n' "$(cat /etc/os-release)"

parameter expansion

via

parameter Set and Not Null parameter Set But Null parameter Unset
${parameter:-word} substitute with parameter substitute with word substitute with word
${parameter-word} substitute with parameter substitute with null substitute with word
${parameter:=word} substitute with parameter assign word assign word
${parameter=word} substitute with parameter substitute with null assign word
${parameter:?word} substitute with parameter error, exit error, exit
${parameter?word} substitute with parameter substitute with null error, exit
${parameter:+word} substitute with word substitute with null substitute with null
${parameter+word} substitute with word substitute with word substitute with null

redirection

via

syntax meaning POSIX compliance
>file redirect stdout to file
1>file redirect stdout to file
2>file redirect stderr to file
>file 2>&1 redirect stdout and stderr to file
&>file redirect stdout and stderr to file 🚫
>>file 2>&1 append stdout and stderr to file
&>>/file append stdout and stderr to file 🚫

rename files

brew install --upgrade rename && # via \
rename --dry-run --verbose --subst searchword replaceword *

replace

recursively replace each file’s first line that begins with #!, and which later contains /bin/bash, /bin/sh, or /bin/ash, with #!/usr/bin/env zsh (via)

command find -- . \
  -type f \
  -exec sed \
  -e '/^#!.*\/bin\/b\{0,1\}a\{0,1\}sh$/ {' \
  -e 's//#!\/usr\/bin\/env zsh/' \
  -e ':a' \
  -e '$! N' \
  -e '$! b a' \
  -e '}' \
  {} ';'

split enormous files into something manageable

if your example.csv has too many rows (via)
split -l 2000 example.csv; for i in *; do mv "$i" "$i.csv"; done

SSH

ls on Windows

dir # via

variables

$PWD # the name of the current directory and its entire path
${PWD##*/} # via the name of only the current directory

wget

wget_server='example.com'; if command -v -- wget2 >/dev/null 2>&1; then utility='wget2'; else utility='wget'; fi; \ command "${utility-}" --level=0 --mirror --continue --verbose \ --append-output=./"${wget_server-}".log --execute robots=off --restrict-file-names=nocontrol --timestamping --debug --recursive --progress=bar --no-check-certificate --random-wait \ --referer=https://"${wget_server-}" --adjust-extension --page-requisites --convert-links --server-response \ https://"${wget_server-}"; unset -v -- wget_server utility

Wi-Fi

Windows password

netsh wlan show profile WiFi-name key=clear # via

macOS password

security find-generic-password -wa ExampleNetwork # via

Xcode

signing

PRODUCT_BUNDLE_IDENTIFIER = net.LucasLarson.$(PRODUCT_NAME:rfc1034identifier);
PRODUCT_NAME = $(PROJECT_NAME) || $(PRODUCT_NAME:c99extidentifier) || $(TARGET_NAME)
DEVELOPMENT_TEAM = "$(DEVELOPMENT_TEAM)";
DevelopmentTeam = "$(DEVELOPMENT_TEAM)";
WARNING_CFLAGS = $(inherited) $(WAX_ANALYZER_FLAGS)

Search the .pbxproj file for project|product|development|example|public|sample|organization|target|ident|dir.

Zsh

array types

<<<${(t)path-} # via

initialization

Zsh sources in order loaded:

  1. /etc/zshenv
  2. ~/.zshenv
  3. /etc/zprofile
  4. ~/.zprofile
  5. /etc/zshrc
  6. ~/.zshrc
  7. /etc/zlogin
  8. ~/.zlogin
  9. /etc/zlogout
  10. ~/.zlogout

troubleshooting

Add zmodload zsh/zprof at the top of ~/.zshrc and zprof at the bottom of it. Restart restart to get a profile of startup time usage. via

housekeeping

docker

docker system prune --all # via

brew

brew doctor --debug --verbose && \
brew cleanup --debug --verbose && # via \
brew audit cask --strict --token-conflicts

npm

npm audit fix && \
npm doctor && # creates empty node_modules directories \
find -- node_modules -links 2 -type d -delete # deletes them

gem

gem cleanup --verbose

Xcode, JetBrains, Carthage, Homebrew

trash_developer='1'; command sleep 1; set -o xtrace; trash_date="$(command date -u -- '+%Y%m%d%H%M%S')" \
command mkdir -p -- "${HOME%/}"'/Library/Developer/Xcode/DerivedData' && command mv -- "${HOME%/}"'/Library/Developer/Xcode/DerivedData' "${HOME%/}"'/.Trash/Xcode-'"${trash_date-}" \
command mkdir -p -- "${HOME%/}"'/Library/Developer/Xcode/UserData/IB Support' && command mv -- "${HOME%/}"'/Library/Developer/Xcode/UserData/IB Support' "${HOME%/}"'/.Trash/Xcode⁄UserData⁄IB Support-'"${trash_date-}" \
command mkdir -p -- "${HOME%/}"'/Library/Caches/JetBrains' && command mv -- "${HOME%/}"'/Library/Caches/JetBrains' "${HOME%/}"'/.Trash/JetBrains-'"${trash_date-}" \
command mkdir -p -- "${HOME%/}"'/Library/Caches/org.carthage.CarthageKit/DerivedData' && command mv -- "${HOME%/}"'/Library/Caches/org.carthage.CarthageKit/DerivedData' "${HOME%/}"'/.Trash/Carthage-'"${trash_date-}" \
command mkdir -p -- "${HOME%/}"'/Library/Caches/Homebrew/downloads' && command mv -- "${HOME%/}"'/Library/Caches/Homebrew/downloads' "${HOME%/}"'/.Trash/Homebrew-'"${trash_date-}" \
command -v -- brew >/dev/null 2>&1 && { command brew autoremove --verbose; command brew cleanup --prune=all --verbose; }; { set +o xtrace; unset -v -- trash_developer; unset -v -- trash_date; } 2>/dev/null; printf '\n\n\360\237%s\232\256  data successfully trashed\n' "${trash_developer-}"

delete

rm -ri /directory # via
rm  -i /document.txt # -i stands for interactive

empty directories

make a list of empty folders inside and beneath current directory . (via)
find -- . -type d -links 2 -print
if satisfied with the results being lost and gone forever, execute:
find -- . -type d -links 2 -delete

compare two folders

diff --recursive /path/to/folder1 /path/to/folder2 # via

purge memory cache

sudo purge # via