Skip to content

Latest commit

 

History

History
569 lines (410 loc) · 21.5 KB

CodeSnippets.md

File metadata and controls

569 lines (410 loc) · 21.5 KB

Code snippets

dotfiles

add

manual

lists
applications
command find -- /System/Applications /Applications -maxdepth 3 -type d -name '*.app' -print0 | command xargs -0 basename -a -s '.app' -- | LC_ALL='C' command sort -u | LC_ALL='C' command sort -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
printf '%s\n' "${MANPATH-}" | sed -e 'y/:/\n/'
man pages

Definintions of the numbers that follow man commands (via)

section contents
1 Executable programs or shell commands
2 System calls (functions provided by the kernel)
3 Library calls (functions within program libraries)
4 Special files (usually found in /dev)
5 File formats and conventions, /etc/passwd, for example
6 Games
7 Miscellaneous (including macro packages and conventions)
8 System administration commands (usually only for root)
pip packages
{ command pip list || command pip3 list; } 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

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' ')' -print |
  command xargs wc |
  LC_ALL='C' command sort -n

search

grep

search for the word “example” inside the current directory which is “.”
grep -i -n -r 'example' .

locate all

for example, locate all JPEG files in the current directory . and below:
command find -- . -type f '(' -name '*.jpg' -o -name '*.JPEG' -o -name '*.JPG' -o -name '*.jpeg' ')'

PATH

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

executables

print -l ${^path-}/*(-*N) # via

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 '*/.*' -type d -exec chmod -- 755 '{}' '+'
command find -- . ! -path '*/.*' -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 . >>./cpplint.txt

run cppcheck recursively

cppcheck --force -I $CPATH . >>./cppcheck.txt

compile all files of type .𝑥 in a directory

C

via, via
gcc -std=c89 --verbose -save-temps -v -Wall -Wextra -pedantic *.c

C++

g++ -std=c++2a --verbose -Wall -Wextra -pedantic -save-temps -v -pthread -fgnu-tm -lm -latomic -lstdc++ *.cpp

Clang

clang++ -std=c++2a --verbose -Wall -Wextra -pedantic -v -lm -lstdc++ -pthread -save-temps *.cpp

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 parameter substitute word substitute word
${parameter-word} substitute parameter substitute null substitute word
${parameter:=word} substitute parameter assign word assign word
${parameter=word} substitute parameter substitute null assign word
${parameter:?word} substitute parameter error, exit error, exit
${parameter?word} substitute parameter substitute null error, exit
${parameter:+word} substitute word substitute null substitute null
${parameter+word} substitute word substitute word substitute 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)

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

ssh username@example.com

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 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 -empty -type d -delete # deletes them via

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')"_"$(command awk -- 'BEGIN {srand(); print srand()}')" \
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 -- trash_developer; unset -- 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 -empty -print
if satisfied with the results being lost and gone forever, execute:
find -- . -type d -empty -delete

compare two folders

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

purge memory cache

sudo purge # via