# Code snippets
- [dotfiles](#dotfiles)
- [lists](#lists)
- [applications](#applications)
- [Homebrew](#homebrew)
- [MANPATH](#manpath)
- [man pages](#man-pages)
- [pip packages](#pip-packages)
- [apk](#apk)
- [testing](#testing)
- [list everything recursively in a directory](#list-everything-recursively-in-a-directory)
- [with full paths](#with-full-paths)
- [and metadata](#and-metadata)
- [lines, words, characters](#lines-words-characters)
- [search](#search)
- [`grep`](#grep)
- [locate all](#locate-all)
- [PATH](#path)
- [executables](#executables)
- [text editing](#text-editing)
- [export output](#export-output)
- [sort](#sort)
- [EOL and EOF encoding](#eol-and-eof-encoding)
- [make invisible](#make-invisible)
- [create an alias](#create-an-alias)
- [launch services](#launch-services)
- [reset](#reset)
- [repair site disk permissions](#repair-site-disk-permissions)
- [date modified modify](#date-modified-modify)
- [case-naming conventions](#case-naming-conventions)
- [C, C++](#c-c)
- [flags](#flags)
- [C++ features before wide support](#c-features-before-wide-support)
- [run `cpplint` recursively](#run-cpplint-recursively)
- [run `cppcheck` recursively](#run-cppcheck-recursively)
- [compile all files of type .đ„ in a directory](#compile-all-files-of-type-đ„-in-a-directory)
- [C](#c)
- [C++](#c-1)
- [Clang](#clang)
- [Gatekeeper](#gatekeeper)
- [Git](#git)
- [`git add`](#git-add)
- [`git diff`](#git-diff)
- [`git commit`](#git-commit)
- [with subject and body](#with-subject-and-body)
- [in the past](#in-the-past)
- [`git config`](#git-config)
- [editor](#editor)
- [`git tag`](#git-tag)
- [Numbers](#numbers)
- [Affixes](#affixes)
- [Operating system](#operating-system)
- [Identify](#identify)
- [parameter expansion](#parameter-expansion)
- [redirection](#redirection)
- [rename files](#rename-files)
- [replace](#replace)
- [split enormous files into something manageable](#split-enormous-files-into-something-manageable)
- [SSH](#ssh)
- [`ls` on Windows](#ls-on-windows)
- [variables](#variables)
- [wget](#wget)
- [Wi-Fi](#wi-fi)
- [Windows password](#windows-password)
- [macOS password](#macos-password)
- [Xcode](#xcode)
- [signing](#signing)
- [Zsh](#zsh)
- [array types](#array-types)
- [initialization](#initialization)
- [troubleshooting](#troubleshooting)
- [housekeeping](#housekeeping)
- [docker](#docker)
- [brew](#brew)
- [npm](#npm)
- [gem](#gem)
- [delete](#delete)
- [compare two folders](#compare-two-folders)
- [purge memory cache](#purge-memory-cache)
## dotfiles
### lists
#### applications
```shell
find -- \
/System/Applications \
/Applications \
-path '/System/Applications/*/*/*' -prune -o \
-path '/Applications/*/*/*' -prune -o \
-name '*.app' \
-print 2>/dev/null |
sed -e 's/.*\/\(.*\)\.app/\1/' |
LANG='C' LC_ALL='C' sort -f
```
On Alpine Linux, generate a list of installed packages with:
`apk --verbose --verbose info | LANG='C' LC_ALL='C' sort #` [via](https://wiki.alpinelinux.org/wiki/Special:PermanentLink/10079#Listing_installed_packages)
##### Homebrew
```shell
brew list -1
```
##### MANPATH
```shell
printf -- '%s\n' "${MANPATH-}" |
sed -e 's/:/\n/g'
```
###### man pages
Definitions of the numbers that follow `man`Â commands ([via](https://web.archive.org/web/20200627082020id_/manpages.ubuntu.com/cgi-bin/search.py?q=man&titles=Title#distroAndSection))
| 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
```shell
{ python -m pip list --format=columns || python -m pip3 list --format=columns || python3 -m pip list --format=columns || python3 -m pip3 list --format=columns; } 2>/dev/null
```
## apk
### testing
`apk add foo #` unavailable? `\`
`#` then try `\`
`apk add foo@testing #` [via](https://web.archive.org/web/20201014175951id_/stackoverrun.com/ja/q/12834672#text_a46821207)
## list everything recursively in a directory
### with full paths
`find -- .` # [via](https://www.cyberciti.biz/faq/how-to-list-directories-in-linux-unix-recursively/)
#### and metadata
```shell
find -- . -exec ls -d -- {} +
```
#### lines, words, characters
in, for example, a C++ project directory, measuring only `.cpp` and `.hpp`
files. [via](https://web.archive.org/web/0id_/github.com/bryceco/GoMap/issues/495#issuecomment-780111175)
```shell
find -- . '(' -name '*.cpp' -o -name '*.hpp' ')' -exec wc -- {} + |
LANG='C' LC_ALL='C' sort -n
```
## search
### `grep`
search for the word âexampleâ inside the current directory which is â.â
```shell
find -- . \
-type f \
-exec grep -i -n -e 'example' -- {} +
```
### locate all
for example, locate all JPEG files in the current directory `.` and below:
```shell
find -- . '(' -name '*.jpg' -o -name '*.JPEG' -o -name '*.JPG' -o -name '*.jpeg' ')' -type f
```
## PATH
```shell
printf -- '%s\n' "${PATH-}" |
sed -e 's/:/\n/g'
```
### executables
```shell
printf -- '%s\n' "${PATH-}" | sed -e 's/:/\n/g' | while IFS='' read -r -- directory; do test -d "${directory-}" && find -- "${directory-}" -path "${directory-}"'/*/*' -prune -o -path "${directory-}"'/*' ! -type d -perm -700 -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
`env >./example.txt` # save an unordered list of `env` variables
`env | LANG='C' LC_ALL='C' sort >./example.txt` # [via](https://howtogeek.com/439199/15-special-characters-you-need-to-know-for-bash) save the variables in an alphabetically ordered list
### EOL and EOF encoding
find `(?
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](https://reddit.com/comments/1qt0z#t1_c1qtge)):
```shell
ln -s existing_file shortcut_to_file
```
## launch services
### reset
remove bogus entries from Finderâs âOpen Withâ menu ([via](https://github.com/mathiasbynens/dotfiles/blob/e42090bf49f860283951041709163653c8a2c522/.aliases#L69-L70))
`/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](https://wordpress.org/support/article/hardening-wordpress/#changing-file-permissions)
```shell
find -- . -path '*/.*' -prune -o -type d -exec chmod -- 755 {} +
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 `
`#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](https://github.com/jonreid/XcodeWarnings/issues/8#partial-discussion-header)
`-lstdc++ #` [via](https://web.archive.org/web/20200517174250id_/unspecified.wordpress.com/2009/03/15/linking-c-code-with-gcc/#post-54) but this might â or might not â be helpful on macOS using gcc or g++
#### C++ features before wide support
for example, C++17âs ``
`-lstdc++fs`
### run `cpplint` recursively
```shell
cpplint --verbose=0 --linelength=79 --recursive --extensions=c++,cc,cp,cpp,cxx,h,h++,hh,hp,hpp,hxx .
```
### run `cppcheck` recursively
```shell
cppcheck --force -I "${CPATH-}" .
```
### compile all files of type .đ„ in a directory
#### C
[via](https://stackoverflow.com/q/32029445), [via](https://stackoverflow.com/q/33662375)
```shell
find -- . -path './*/*' -prune -o -name '*.c' -type f -exec gcc -std=c89 --verbose -save-temps -v -Wall -Wextra -pedantic -- {} +
```
#### C++
```shell
find -- . -path './*/*' -prune -o -name '*.cpp' -type f -exec g++ -std=c++2a --verbose -Wall -Wextra -pedantic -save-temps -v -pthread -fgnu-tm -lm -latomic -lstdc++ -- {} +
```
#### Clang
```shell
find -- . -path './*/*' -prune -o -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](https://github.com/herrbischoff/awesome-macos-command-line/blob/bd25a136655e63fcb7f3462a8dc7105f30093e54/README.md#manage-gatekeeper)
## Git
### `git add`
[via](https://stackoverflow.com/a/15011313)
| 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
```shell
git diff --raw
```
### `git commit`
#### with subject and body
`git commit --message='subject' --message='body' #` [via](https://stackoverflow.com/a/40506149)
#### 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](https://stackoverflow.com/questions/3895453/how-do-i-make-a-git-commit-in-the-past#comment97787061_3896112)
### `git config`
#### editor
Vim
`git config --global core.editor /usr/local/bin/vim`
Visual Studio Code
```shell
git config --global core.editor "code --wait"
```
### `git tag`
`git tag vđ.đ.đ #` where đ, đ, and đ are non-negative integers representing [SemVer](https://github.com/semver/semver/blob/8b2e8eec394948632957639dfa99fc7ec6286911/semver.md#summary) (semantic versioning) major, minor, and patch releases
`git push origin vđ.đ.đ #` push the unannotated tag [via](https://stackoverflow.com/a/5195913)
## 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](https://apple.stackexchange.com/a/368244)Â `\`
`printf '\n\140sw_vers\140:\n%s\n\n' "$(sw_vers)";Â \`
`command -v -- lsb_release >/dev/null 2>&1 && #` [via](https://web.archive.org/web/20201023154958id_/linuxize.com/post/how-to-check-your-debian-version/#checking-debian-version-from-the-command-line)Â `\`
`printf '\n\140lsb_release --all\140:\n%s\n\n' "$(lsb_release --all)";Â \`
`[ -r /etc/os-release ] && #` [via](https://web.archive.org/web/20201023154958id_/linuxize.com/post/how-to-check-your-debian-version/#checking-debian-version-using-the-etcos-release-file)Â `\`
`printf '\140cat /etc/os-release\140:\n%s\n\n' "$(cat /etc/os-release)"`
## parameter expansion
[via](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02)
| | _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](https://askubuntu.com/a/350216)
| 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](https://stackoverflow.com/a/31694356)Â `\`
`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](https://stackoverflow.com/a/11458836))
```shell
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](https://web.archive.org/web/20181210131347/domains-index.com/best-way-view-edit-large-csv-files/#post-12141))
`split -l 2000 example.csv; for i in *; do mv "$i" "$i.csv"; done`
## SSH
```shell
ssh username@example.com
```
### `ls` on Windows
`dir` # [via](https://stackoverflow.com/a/58740114)
## variables
`$PWD` # the name of the current directory and its entire path
`${PWD##*/}` # [via](https://stackoverflow.com/a/1371283) 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; \
"${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 >/dev/null 2>&1 || wget_server=''; unset utility >/dev/null 2>&1 || utility=''`
## Wi-Fi
### Windows password
`netsh wlan show profile WiFi-name key=clear #` [via](https://redd.it/d5vknk)
### macOS password
`security find-generic-password -wa ExampleNetwork #` [via](https://labnol.org/software/find-wi-fi-network-password/28949)
## 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](https://til.hashrocket.com/posts/7evpdebn7g-remove-duplicates-in-zsh-path)
### initialization
Zsh sources in order loaded:
1. `/etc/zshenv`
1. `~/.zshenv`
1. `/etc/zprofile`
1. `~/.zprofile`
1. `/etc/zshrc`
1. `~/.zshrc`
1. `/etc/zlogin`
1. `~/.zlogin`
1. `/etc/zlogout`
1. `~/.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](https://web.archive.org/web/20210112072135id_/reddit.com/r/zsh/comments/kums6q/zsh_very_slow_to_open_how_to_debug/gisz7nc/)
## housekeeping
### docker
`docker system prune --all #` [via](https://news.ycombinator.com/item?id=25547876#25547876)
### brew
`brew doctor --debug --verbose &&Â \`
`brew cleanup --debug --verbose && #` [via](https://stackoverflow.com/a/41030599)Â `\`
`brew audit cask --strict --token-conflicts`
### npm
`npm audit fix && \`
`npm doctor && #` creates empty `node_modules` directories `\`
`find -- node_modules -type d -exec rmdir -- {} + >/dev/null 2>&1 || true` # deletes them if empty
### gem
`gem cleanup --verbose`
## delete
`rm -iR /directory #` [via](https://github.com/herrbischoff/awesome-macos-command-line/blob/cf9e47c26780aa23206ecde6474426071fb54f71/README.md#securely-remove-path-force)
`rm -i  /document.txt # -i` stands for interactive
### compare two folders
`diff --recursive /path/to/folder1 /path/to/folder2` # [via](https://github.com/herrbischoff/awesome-macos-command-line/blob/cf9e47c26780aa23206ecde6474426071fb54f71/README.md#compare-two-folders)
### purge memory cache
`sudo purge` # [via](https://github.com/herrbischoff/awesome-macos-command-line/blob/cf9e47c26780aa23206ecde6474426071fb54f71/README.md#purge-memory-cache)