Dealing with some minified json, switching to iTerm, doing `pbpaste | json_pp | pbcopy` and having a clean output is _so_ nice.
pbfilter() {
if [ $# -gt 0 ]; then
pbpaste | "$@" | pbcopy
else
pbpaste | pbcopy
fi
}
Then you can use something like `pbfilter json_pp` or `pbfilter base64 -d` or `pbfilter sed 's/this/that/'` or whatever.This version also can also act as a plain-text-only filter. If you just use `pbfilter` with no argument, it'll remove any formatting from the text in the pasteboard, leaving just straight plain text.
It does have a some limitations, though: you can't use it with an alias, or pipeline, or anything complex like that. The filter command must be a single regular command (or function) and its arguments.
# This will remove Windows double-spaced empty lines from your copy/paste buffer
alias winlines="sed '/^$/{$!{N;s/\n//;};}'"
# pbw = [P]aste [B]uffer to fix [W]indows line endings
alias pbw="pbpaste | winlines | pbcopy"
Also - if you want `pbpaste` and `pbcopy` on Linux... # imitate MacOS's paste buffer copy/paste:
alias pbcopy='xsel --clipboard --input'
alias pbpaste='xsel --clipboard --output'This means you can do things like copy an image from the terminal and paste it into a graphical program like a browser or chat client and vice-versa. Also can be very useful in shell scripts for desktop automation.
The workaround on MacOS is to use AppleScript via `osascript` to `set the clipboard to...`.
[0] https://github.com/astrand/xclip
[1] https://github.com/bugaevc/wl-clipboard pbpaste | vipe | pbcopy
Where vipe is a util for inserting your editor (vim) in the middle of a pipe. From: https://joeyh.name/code/moreutils/then just highlight any youtube link and COPY
later when I have time, I can use quicklook to browse directory of youtube videos.
git diff | pbcopy
pbpaste | git apply`cat ~/.ssh/mykey.pub | pbcopy`
Now, for your Mac example — if that's a specific pipeline you often use, you can write a Service menu entry to do it in place, without switching to a terminal.
#!/usr/bin/env python3
import sys
import json
print(json.load(sys.stdin))Being able to populate or read from the system clipboard (or secondary clipboard!), or to feed it, including by reading from or writing to pipes is wonderful.
select all in a terminal window with pages of log data and cmd-c copy; find the one phrase you want to find in that data and cmd-e to put it in the find pasteboard; cmd-n new window, type pbg to isolate the log lines.
alias clip='pbcopy <'
I do this a lot as well, but just paste the minified json directly into VS Code and then OPT+SHIFT+F to format it.
pbpaste > tmp; vim tmp; cat tmp | pbcopy; rm tmp;
I also use pbpaste to append various notes to files, but since pbpaste doesnt have a newline at the end I wind up using: echo "$(pbpaste)" >> notes.txt:w !pbcopy
or visual selection, and then :w !pbcopy
You can simulate a really bad network. Latency, bandwidth, packet loss etc. Great for testing but also if people insist on cameras being on. Just screw up the connection so bad that everyone gets annoyed with your blocky image and robot voice and suggest you turn off video and then you make it 'magically' ok - lol
Thanks for sharing.
You can use dnctl and pfctl on macOS to do similar things and more.
alias tab='open . -a iterm'
alias phpstorm='open -a "PhpStorm"'
alias smerge='open -a "Sublime Merge"'
etc. I use those more than I do the Open/Recents dialogs in the respective apps. $ fd 's(merge|ubl)$' /Applications/Sublime*
/Applications/Sublime Merge.app/Contents/SharedSupport/bin/smerge
/Applications/Sublime Text.app/Contents/SharedSupport/bin/sublhttps://github.com/davatorium/rofi
Looks like this:
https://i.imgur.com/Hm9TGeV.jpg
In a vscode terminal I just use the alias "o" and it opens that at the correct location, then I can navigate and pick a file to open in the editor.
alias finder='open .'But if you just open a new tab, you'll be in the same $CWD in the new tab? Am I missing some trick here?
"So, I used the msf module that invokes `say` on a client's laptop"
So I added a fish command completion script that plays a beep with afplay if the task took longer than 5 seconds. It helps me get back on task for those “just long enough” tasks that I run.
If you take a screen shot (command + shift + 4) or partial screen shot (command + shift + control + 4) you can save it directly to an image file with:
pngpaste filename.png
I administer that machine for her (to the extent that such a thing is needed), and so I knew (a) her login and (b) that SSH was open.
Me combining remote access with "say" made for a very memorable morning for that kid.
say "process failure" -v trinoids
you can find all the available voices with say -v '?'
or from Accessibility>Spoken-Content>System-voice>Manage-voicesSince then I've moved to Amphetamine (same purpose menu-bar app, even stronger chemicals, has timed keep-awake etc).
mkdir MyIcon.iconset
cp Icon1024.png MyIcon.iconset/icon_512x512@2x.png
sips -z 16 16 Icon1024.png --out MyIcon.iconset/icon_16x16.png
sips -z 32 32 Icon1024.png --out MyIcon.iconset/icon_16x16@2x.png
sips -z 32 32 Icon1024.png --out MyIcon.iconset/icon_32x32.png
sips -z 64 64 Icon1024.png --out MyIcon.iconset/icon_32x32@2x.png
sips -z 128 128 Icon1024.png --out MyIcon.iconset/icon_128x128.png
sips -z 256 256 Icon1024.png --out MyIcon.iconset/icon_128x128@2x.png
sips -z 256 256 Icon1024.png --out MyIcon.iconset/icon_256x256.png
sips -z 512 512 Icon1024.png --out MyIcon.iconset/icon_256x256@2x.png
sips -z 512 512 Icon1024.png --out MyIcon.iconset/icon_512x512.png
iconutil -c icns MyIcon.iconset
As a bonus, generate .ico with ffmpeg: ffmpeg -i MyIcon.iconset/icon_256x256.png icon.ico
Incidentally, does anyone know enough about the way sips scales PNGs to confirm that it makes sense to create the 16px version straight from 1024px, as opposed to basing it off 32px (and all the way up)? I.e., is it better to downscale in fewer steps (as currently) or in smaller steps?qlmanage -t -s 1024x1024 -o MyIcon.iconset/Icon1024.png icon.svg
That said I just checked some macOS system icons (get info on app, select icon, copy, create new document in Preview.app) and they don't seem to be hand adjusted any more.
Others have mentioned the “say” utility for speech synthesis. There is a lot you can do with it, it supports the TUNE format, which allows you to "shape the overall melody and timing of an utterance... for example ... to make an utterance sound as if it is spoken with emotion".
See: Apple's Speech Synthesis Programming Guide, https://josh8.com/blog/img/speech-synthesis.pdf
I also wrote more about this here: https://josh8.com/blog/commandline-audio-mac.html
Also, hidutil (https://developer.apple.com/library/archive/technotes/tn2450...).
Example:
hidutil property --set '{"UserKeyMapping":[{"HIDKeyboardModifierMappingSrc":0x700000049,"HIDKeyboardModifierMappingDst":0x700000065}]}'
For my PC keyboard, remaps "Ins" (normally useless under macOS) to something ("PC Execute") I can trap and remap with Keyboard Maestro. hidutil property --set '{"UserKeyMapping":[{"HIDKeyboardModifierMappingSrc":0x700000064,"HIDKeyboardModifierMappingDst":0x700000035}]}'
Remaps top left key on Euro-style keyboards from useless "paragraph" to useful "backtick". hdiutil detach /Volumes/some-usb-drive
hdiutil makehybrid -joliet -o foo.iso ./srcfolder/It’s indispensable.
Sadly the app does get the shell's environment and it can't be disabled:
Opened applications inherit environment variables just as if you had
launched the application directly through its full path. This behavior
was also present in Tiger.
Why this matters, e.g with vscode: - ensure vscode is fully closed
- enter project directory, something sets vars in your shell (you manually or automatically via direnv)
- code .
- vscode process now has the env from the shell it was started
- open another directory from the UI
- vscode forks and inherits from its parent process, thus the other project window has the original shell's env
- go to another directory
- code .
- vscode finds out it's already running, forks and opens another window. this window has the original shell env
- fully quit vscode and reopen it, but via the app in /Applications
- vscode opens, now has a blank environment for its main process, and forks form there to restore previous windows, which now lack the environment they had
It's a) completely inconsistent and b) dangerous: imagine the original shell had a setting or secret in an env var that was shared to the second project (e.g virtualenv, deploy target, deployment key...)The same issue can happen with other apps but also tmux (the tmux daemon is spawned from the first tmux command, and then subsequent sessions from tmux-server; doing it another way is possible but nontrivial)
https://github.com/microsoft/vscode/issues/15452
https://github.com/microsoft/vscode/issues/108804#issuecomme...
open .
if you need to drag a file somewhere. One thing that kind of breaks my muscle memory here is the opposite, something like firefox file.html
doesn't work and you have to fiddle with the arguments to get open to launch a non-default application.Edit: Found https://www.macinstruct.com/tutorials/how-to-check-your-macs... which says:
"The networkquality tool uses Apple’s CDN (https://mensura.cdn-apple.com/api/v1/gm/config) as a target"
The contents of this file (for me):
{ "version": 1,
"test_endpoint": "sesto4-edge-bx-021.aaplimg.com",
"urls": {
"small_https_download_url": "https://mensura.cdn-apple.com/api/v1/gm/small",
"large_https_download_url": "https://mensura.cdn-apple.com/api/v1/gm/large",
"https_upload_url": "https://mensura.cdn-apple.com/api/v1/gm/slurp",
"small_download_url": "https://mensura.cdn-apple.com/api/v1/gm/small",
"large_download_url": "https://mensura.cdn-apple.com/api/v1/gm/large",
"upload_url": "https://mensura.cdn-apple.com/api/v1/gm/slurp"
}
}When I was commuting daily displayplacer was even more indispensable but even for just unplugging my mac and using the internal screen vs my monitors I get a ton of value out of this tool.
(There's BetterDisplay - formerly BetterDummy - but it introduces noticeable input lag for me.)
I use pbcopy and pbpaste probably all day long and always miss it in Linux environments.
# hide desktop icons and folders
defaults write com.apple.finder CreateDesktop 0
killall Finder # restarting Finder is required
# unhide desktop icons and folders
defaults write com.apple.finder CreateDesktop 1
killall Finder # restarting Finder is required
I made myself a convenient bash alias for this which lets me simply toggle the desktop on and off
Here is a gist: https://gist.github.com/berndverst/6f58c0d6aedddb6c06c23e57d... toggledesktop () {
if [[ $(defaults read com.apple.finder CreateDesktop) -eq "0" ]]
then
export SHOWDESKTOP=1;
echo "Unhiding Desktop icons"
else
export SHOWDESKTOP=0;
echo "Hiding Desktop icons"
fi
defaults write com.apple.finder CreateDesktop $SHOWDESKTOP
killall Finder
}Although: the introduction of Stacks to the macOS desktop was a great thing — I always show that feature to anyone whose Desktop is helplessly cluttered with files.
If you want more like this, I also have another page full of lesser well-known macOS tips and tricks: https://saurabhs.org/macos-tips
alias list-functions='functions -x4'
alias list-function-names='functions +'
alias list-aliases='alias'
alias list-alias-names='alias +'
alias list-commands='print -raC2 ${(kv)commands} | sort'
alias list-command-names='print -roC1 ${(k)commands}'
alias list-builtins='print -raC2 ${(kv)builtins} | sort'
alias list-builtin-names='print -roC1 ${(k)builtins}'
alias list-everything='whence -cm "[^_]*"'
alias list-everything-names='whence -wm "[^_]*"'
Edit: another commenter posted what looks to be comprehensive docs/lists here: https://news.ycombinator.com/item?id=36492487 /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister
Manage file extended attributes (such as quarantine): xattr
Execute a script (AppleScript or JavaScript): osascript -e <statement>``` #!/usr/bin/env bash
set -u
title=${2:-Shell}
msg=$1
osascript -e "display notification \"$1\" with title \"$title\""
```As `~/bin/,notify` and put it at the end of long-running commands:
``` run_this_program && ,notify "Long program is done!" ```
-d Create an assertion to prevent the display from sleeping.
-i Create an assertion to prevent the system from idle sleeping.
-m Create an assertion to prevent the disk from idle sleeping.
-s Create an assertion to prevent the system from sleeping. This
assertion is valid only when system is running on AC power.1. bat: A `cat` clone with syntax highlighting and Git integration.
2. htop: Interactive process viewer, a better alternative to `top`.
3. fzf: Command-line fuzzy finder to quickly search files, command history, etc.
4. tldr: Community-driven man pages with practical examples.
5. ripgrep (rg): Extremely fast text search tool, recursively searches directories for a regex pattern.
6. tmux: Terminal multiplexer to run multiple terminal sessions within a single window.
7. autoenv: Automatically source environment variables based on the current directory.
8. hub: Extends git with extra features and commands for GitHub.
9. ncdu: Disk usage analyzer with an ncurses interface.
10. jq: Lightweight command-line JSON processor.
11. sshfs: Mount a remote filesystem using SFTP.
12. watch: Execute a program periodically, showing output fullscreen.
13. fd: Simpler and faster alternative to `find`.
14. z: Jump around directories based on frequent use.
15. lazygit: Simple terminal UI for git commands.
Most of them I already knew, but z seems like an interesting tool. The docs are here <https://github.com/rupa/z>:
z foo cd to most frecent dir matching foo
z foo bar cd to most frecent dir matching foo, then bar
z -r foo cd to highest ranked dir matching foo
z -t foo cd to most recently accessed dir matching foo
z -l foo list all dirs matching foo (by frecency)
Might start using it, if I'm not too stuck in my habits.I wouldn't do that. I treat ChatGPT as public.
But it's a good list nevertheless
Many a times, a website says "file needs to be no bigger than 2 MB", and I need to scramble with Preview app to resize teh app until it falls below that limit. A cli tool for that action would be very handy.
You can even do bulk cmds with cli on images:
for x in ls *.webp; do ffmpeg -i $x ${x%.webp}.png; done
reformats images from webp to png in a directory. magick mogrify -monitor -format jpg *.png -compress 70
reformats and compresses pngs to be jpg in a directory convert original.jpg -define jpeg:extent=2MB output.jpg
The result will be around 2MB in size (in both directions).I had problems with some slices on a disk today, and was not able to fix it with the graphical Disk Utility that comes with macOS. These slices were remnants from experimenting with running Asahi Linux on the machine in the past.
I knew there had to be a way to fix it with diskutility cli program.
I found a thread, and the solution for what to do in such situation.
https://apple.stackexchange.com/questions/411544/cant-reclai...
Now the disk can be fully utilised by macOS again.
~ um prevent my mac from sleeping for 30m
caffeinate -u -t 1800
don't see what you're looking for? try providing more context /System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport
I set an alias in my shell so this is just 'airport', lets you interact with the wifi settings - I particularly like 'airport -s' for doing a scan of the local wifi networks, since it shows signal strength and channel information right there, which is helpful when troubleshooting.https://osxdaily.com/2014/06/11/use-ditto-copy-files-directo...
> It's handy for things like remapping CapsLock to anything
It's a built-in MacOS feature that you can find in the keyboard settings.
macOS 13 Ventura ships with a customized `iperf3` called `iperf3-darwin` adding features like QUIC/L4S/MPTCP.
afconvert music.wav -o music_160kbps_aac.m4a -b 160000 -q 127 -s 2 -f m4af -d 'aac '
lipo(1) lets you operate (replace/extract/thin/etc) on executables and libraries to tailor their supported architectures: lipo <universal exe/dylib> -thin arm64e -output <new apple silicon-only exe/dylib> # 500 megabytes disk image
mb=$((500*2048))
diskutil eraseVolume ExFAT my_ramdisk `hdiutil attach -nomount ram://$mb`https://www.manpagez.com/man/1/fs_usage/
I can't count the number of times a bit of fs_usage foo has helped me dig out of a seriously messy pile of network, file and page fault issues ..
If you type `say os x`, it'll actually speak "oh es ten".
networkQuality is something I really wish I knew about sooner.
I also alias pbcopy / pbpaste on Linux too, so useful!
For example, turn off autohiding of the Dock from commandline:
defaults write com.apple.dock "autohide" -bool "false" && killall Dock
Include the date in screenshots you take: defaults write com.apple.screencapture "include-date" -bool "true"
Here is handy website which documents many of the defaults and their purpose:
https://macos-defaults.com/#%F0%9F%99%8B-what-s-a-defaults-c... say -v Whisper "Weird: Layer zero one"On [2] you might find the aliases to pbutil for X11-based Linuxes.
[0]: If not, why not run apt-get command to install one of them, like xclip?
[1]: https://git.zx2c4.com/password-store/tree/src/password-store...
[2]: https://ostechnix.com/how-to-use-pbcopy-and-pbpaste-commands...
alias sleepoff="sudo pmset -a disablesleep 1"
alias sleepon="sudo pmset -a disablesleep 0"
This fully disables sleep, period. Just make sure you don't leave it unplugged too long, but on Apple Silicon it lasts for quite a long time. open -h AppKit.h
to open any system header file (or I guess any header in the standard include path? It finds stuff from Homebrew too.)qlmanage -t -s 1000x1000 -o ~/Pictures/foo.png ~/Pictures/foo.svg
To turn an square SVG into a PNG without installing anything extra or using an online image tool
It's ls for metadata. Very helpful for getting quick and scripted access to the date/time when and the latitude/longitude where a photograph was taken.
Also, the say command is a lot more versatile than it seems.
Combined with the ability to save the speech to an audio file, my wife uses it as the disc jockey for her little hobby AM radio station. It introduces the song and does little station IDs and such.
You can customize it with dozens of dozens of voices, some in very high quality.
When a song from her Japanese playlists comes on, it switches to one of the Japanese voices. I don't speak Japanese, so I don't know if it actually translates the DJ words into Japanese, but it sounds pretty close to my untrained ears.
security find-generic-password -gw -l "${keychain_id}"
Super helpful for VPN automation scripts, easy logins to things like Vault, etc. The security tool has tons of other handy functions as well.diskutil: modify, verify and repair local disk
hdiutil: manipulate disk images (attach, verify, create, etc)
dscl: Directory Service command line utility (manage users and groups)
scutil: Manage system configuration parameters (useful for checking current DNS configuration and checking reachability to a host).
sysadminctl: It's a secret! No man page. Run without options to get a usage message, but even the usage is apparently incomplete. It's a grab-bag of functionality. I use for adding/removing a temporary build user as part of a CI/CD setup.
# cd to frontmost open finder folder (in Terminal cd to the current top finder window) cdf() { cd "`osascript -e 'tell app "Finder" to POSIX path of (insertion location as alias)'`"; pwd; }
# Copy the frontmost open finder folder Path from Terminal to the Clipboard in MacOS: cpf() { echo "`osascript -e 'tell app "Finder" to POSIX path of (insertion location as alias)'`"|pbcopy; }
# open manpage in preview app: pman() { mandoc -T pdf "$(/usr/bin/man -w $@)" | open -fa Preview; }
# Function to delete a given line in ssh known_hosts file: xho() { line=$1;tFile="$HOME/.ssh/known_hosts";sed -e "${line}d" -i ".tmp" "$tFile";}
https://opensource.apple.com/source/cups/cups-450/cups/doc/h...
macOS software versions:
sw_vers
macOS hardware overview: system_profiler SPHardwareDataType
Convert binary plist to xml plutil -convert xml1 -o out.xml in.plist
A couple of lesser known, but also handy ones to install: brew install dark-mode
brew install duti
> screencapture - take screenshotsBig fan of screencapture. I wanted something similar but for capturing window videos, so I built https://github.com/xenodium/macosrec
I often wrap command line utilites with Emacs functions (don't need to remember invocation flags/structure but also enables batch invocations) https://xenodium.com/recordscreenshot-windows-the-lazy-way
And urls! I use that one in a lot of my scripts. We have a ticket-based workflow, and I can parse out the ticket number from the current git branch, and open the ticket or create a merge requests without having to do anything complicated.
https://www.mattcrampton.com/blog/managing_wifi_connections_...
I use these commands a lot when I'm in a coffeeshop and I'm trying to fine-grain control which wifi connection my laptop is using and dealing with passwords.
IMO OSX's UI for wifi network picking is clunky when you're in an area with >50 wifi networks in range, command line tools are much easier to deal with.
I use this to convert an mp3 to a variable rate m4b for Books:
afconvert -v -s 3 -f m4bf meditation1.mp3[1]: https://developer.apple.com/documentation/xcode/installing-a...
I use open regularly. Often to open a directory in finder and preview a file. Looks like I can just use qlmanage from now on.
Not sure I'd use screencapture manually, but I'm sure there are some automations that could benefit from this.
I would have expected that at the era of AI this would sound a bit better than the Commodore 64 speech synthesis from 80s.
Am I the only one who finds macOS so annoying?
I mean the apps for scroll wheel, alt-tab and what not...
Here are a couple of commands I use quite a lot.
lsof -p <PID>
Lists the open files of the process with process ID <PID>. Very very useful.
fs_usage -w <PID>
This one is mentioned by others here as well, but followed by a <PID> it shows all filesystem activity of the given process. Useful if you want to know where specific settings of an application are stored.
top -u
Obvious what this does, standard command. Sorted by CPU usage.
<some command> | open -ft
Opens the <some command>'s result in your default text editor.
system_profiler
Very useful for finding out stuff. E.g. system_profiler SPNVMeDataType SPSerialATADataType | grep 'BSD Name: disk[0-9]$' | sed 's/.\* //' Gives the device name of all your system's SATA and NVMe SSD's.
sysctl -a
Another way to find out stuff. E.g. sysctl -a | grep hw.memsize Shows the amount of physical memory in your system.
tmutil
Very powerful for managing Time Machine as mentioned by others here. Also useful for other stuff. There is a lot of File I/O on my system due to running at least five VM's all the time. This produces big snapshots. Every now and then my system hung up due to running out of space because of these snapshots. Now I'm running my own "snapshottaper" daemon running every ten minutes keeping only the last 4 snapshots and deleting the rest, using "tmutil listlocalsnapshotdates" and "tmutil deletelocalsnapshots" which eliminates that issue (which is a bug imho).
And some of my often used (tcsh) aliases:
proc, aliased to 'ps -axww -o pid,user,command | grep -v "grep -i" | grep -i \!\* | sed "s/^\ *//"'
Filter the list of running processes for a specific string, e.g. use "proc adobe" to find all running processes by Adobe. I use this a lot.
spf, aliased to 'dig \!* txt | grep "v=spf"'
Useful for finding SPF records for a given domain, e.g. 'spf apple.com'.
mx, aliased to 'dig \!\* mx | grep -v "^;..*" | grep "IN\WMX"'
Same, but for MX records (I maintain e-mail servers, hence these two).
est, aliased to 'netstat -n | grep -i proto ; netstat -n | grep ESTABLISHED | grep -v 127.0.0.1'
List all currently open network connections.
listen, aliased to 'sudo echo -n; sudo lsof -i4 -n -P | grep "\*:" | sed "s/IPv4.*://" | grep LISTEN | sort -n --key=5 | sed "s/ (LISTEN)//" | awk BEGIN\ \{print\ \"COMMAND\ \ \ \ \ \ \ \ \ \ \ PID\ \ \ \ \ \ \ USER\ \ \ \ \ \ \ PORT\"\}\ \{printf\ \"%-10s\ %10s\ %10s\ %10s\\n\"\,\ \$1\,\ \$2\,\ \$3\,\ \$5\}'
List all processes currently listening on network ports.
router, aliased to 'netstat -rn -f inet | grep default | grep -v link | awk \{print\ \$2\} | head -1'
List the currently used internet router.
(I hope all escape characters and such survive posting this, please excuse me if they don't, also my default command shell is tcsh for historical reasons, it was my default shell in the early 1990's. Yes my shell scripts are all #!/bin/sh)
Other than these, I really like using AppleScript and shell scripts together. Using AppleScript I now have my own GUI tools for making disk images using drag-and-drop, compacting sparse images, performing default settings for new installations, switching between virtual machines whilst hiding others, etc.