Comment by klausa

3 years ago

`pbcopy` and `pbpaste` are one of my most-loved in the list.

Dealing with some minified json, switching to iTerm, doing `pbpaste | json_pp | pbcopy` and having a clean output is _so_ nice.

I find that the `pbpaste | something | pbcopy` idiom is common enough that it's worth having a shell function for it:

  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.

I love this flow! Such a powerful and clean way to solve text issues.

    # 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'

I find it so annoying that these only work with plain text and RTF. On X11 there is `xclip`[0] and on Wayland there is `wl-clipboard`[1] both of which support binary file formats either through parsing the header or explicitly setting the MIME type.

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

It's cool to use pbcopy and pbpaste with your phone! Copy some text on the phone, and you can pbpaste it onto the Mac command line. So cool.

  • It creeps me out when the clipboard is unexpectedly shared between my phone and computer. And since the feature seems to turn on randomly but not reliably when I want it to, I’d rather it just didn’t exist.

    • I have a clipboard manager application called "Paste" (creative i know). Its an awesome app for a million reasons. But one thing I like is that it allows me to see and hear when my iphone copy worked.

      So I have it enabled so there is a sound when something goes into the clipboard. Even on my mac, I have come to rely on that audio feedback. But it has the added benefit that when I am using my phone in front of my computer and I copy something on my phone, I immediate (and it is impressively fast... maybe a 200ms delay), I hear the chime that something was added to my clipboard on my mac. So it gives you that good feedback that a copy "worked".

      You can also shift+cmd+V to see the clipboard history, which is another complimentary tool with universal clipboard because if a paste isn't working as expected you can see if the universal copy never "took" (as you mentioned it is semi-unreliable), or if it just got overridden. You can then use the navigator to paste the older item.

      3 replies →

    • For me it’s one of the top benefits of the Apple ecosystem.

      The only drawback is that yes it only works most of the time. And when it doesn’t I get infuriated.

      Glitches happen without any change to settings or network on my side - it works now, and 5 min later doesn’t.

      9 replies →

    • > is unexpectedly shared between my phone and computer

      There was a prompt asking if I wanted to enable it, when I set up my phone/Mac. Same setup screen that asks if you want to enable location, Siri, etc.

    • Disabling Handoff is currently the only way to disable Universal Clipboard.

      * Mac: Go to System Preferences > General > uncheck Allow Handoff.

      * iPhone: Go to Settings > General > Handoff > uncheck Handoff.

I use the following to edit contents of my 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/

  • This is great utility I didn't know about! Thanks!

    But do you know why it doesn't seem to work with the `pbfilter` function?

    If I do directly `pbpaste | vipe | pbcopy`, then it opens vim and the clipboard text is pasted there. But if I run `pbfilter | vipe`, then vim opens with a blank buffer.

       function pbfilter() {
          if [ $# -gt 0 ]; then
              pbpaste | "$@" | pbcopy
          else
              pbpaste | pbcopy
          fi
       }      
    
    

    It seems that the number of args is 0 for some reason

    • I think you have to use `pbfilter vipe`, as the argument to pbfilter is inserted into the middle of the pipe.

I have a script always running that polls for youtube URLs using pbpaste and runs yt-dl

then just highlight any youtube link and COPY

later when I have time, I can use quicklook to browse directory of youtube videos.

So much of my Linux use is over ssh from a MacOS client that I've made a `pbcopy` executable that just pipes stdin over ssh to my MacBook to its pbcopy (with a dedicated ssh key that runs this as a forced command). Makes it super nice to be on an SSH session and `pbcopy` some content to my MacOS clipboard!

Another frequent use I have, applying random diffs with git:

    git diff | pbcopy
    pbpaste | git apply

  • You can also use `git format-patch` and `git am` if you want to apply the same commit to multiple repos, a use-case I sometimes I have.

    • I should use `git format-patch` instead of creating a mock draft PR (which I end up deleting) and modifying the URL to add `.patch` and then downloading the patch file haha. `git format-patch` would probably be faster :)

If I had a nickel for each `cat foo.json | jq | pbcopy`, I'd be a rich man :)

I like to use `pbcopy` when exporting public keys to external services like GitHub.

`cat ~/.ssh/mykey.pub | pbcopy`

  • I love this tool too!

    except one time I quickly typed

    `cat ~/.ssh/mykey | pbcopy`

    And sent it straight away to my coworker on Slack.

    I then spent the rest of the day making a new private key and adding my new pubkey to all of the 1000+ servers I had root access to. I mean we had tools to help but it still wasn’t fun.

    With great power/convenience comes the potential to do dumb things at lightning speeds!

  • You can even simplify this further by feeding `pbcopy` the key directly using file redirection instead of a pipe:

    `pbcopy < ~/.ssh/mykey.pub`

    (I use this all the time myself!)

On Linux I have these wrap xsel or xclip, and likewise open to xdg-open.

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.

  • +1 to the service menu actions. They are so handy, but often forgotten/overlooked. I think maybe a discoverability issue.

Since you mention both pbcopy and iTerm - I love https://github.com/skaji/remote-pbcopy-iterm2. I do most of the work on a remove Linux server, treating my MacBook as mostly a dumb terminal, and being able to transparently copy from the remove to my local clipboard is so nice.

  • I’ll have to try that. More than once I’ve been logged in to a remote host and got “pbcopy not found” “What!?… oh, right.“

  • The tmux integration in iterm is also very nice for remote work if you haven’t tried it out.

    • I have tried it, but for whatever reason I just don't like it. I prefer just running tmux in iTerm with no integration.

      On the topic, you can also integrate tmux with the native clipboard - I have set copy-pipe to the remote pbcopy, so any selection done in tmux get copied to my local clipboard. I also just found out that tmux also support it natively (https://github.com/tmux/tmux/wiki/Clipboard#the-set-clipboar...).

Use the Apple shortcuts app and you can just copy some text and hit a keyboard shortcut. The Shortcuts app lets you run arbitrary shell command.

  • This is interesting, thank you. I've been automating various things with Hammerspoon but (I think) it's limited to what you can reach with either a11y or osascript / the NS dictionary for the app you want to manipulate, but Shortcuts seems to have some actions that aren't in the NS dictionary.

    For instance, in Shortcuts, I see that there's a "Pin Notes" action for Notes.app, but I don't see anything for pinning notes when I open Notes.app with "File -> Open Dictionary..." in Script Editor.

    (In this case it's likely that Notes.app has the a11y bits necessary to run that action from Hammerspoon, but it would probably be easier to go through Shortcuts.)

Yes. I use it a great deal, but I haven't gotten used to using the linux equivalents. I guess that would be either xsel or xclip. Maybe I should create a "pbcopy" that runs one of those. I like to minimize the cognitive load when I switch between mac and linux command line environments.

Oh man. I recently threw together a "j2p" script to make converting between json and python dicts simpler, and combining it with pbcopy/pbpaste will make it so much better:

  #!/usr/bin/env python3
  import sys
  import json
  
  print(json.load(sys.stdin))

  • Or directly from the commandline:

        pbcopy | python -c 'import sys; import json; print(json.load(sys.stdin))' | pbpaste

    • The Python json library is callable as a module:

          pbcopy | python -m json.tool | pbpaste
      

      It has a load options:

          $ python -m json.tool --help
          usage: python -m json.tool [-h] [--sort-keys] [--no-ensure-ascii] [--json-lines] [--indent INDENT | --tab | --no-indent | --compact] [infile] [outfile]
      
          A simple command line interface for json module to validate and pretty-print JSON objects.
      
          positional arguments:
            infile             a JSON file to be validated or pretty-printed
            outfile            write the output of infile to outfile
      
          options:
            -h, --help         show this help message and exit
            --sort-keys        sort the output of dictionaries alphabetically by key
            --no-ensure-ascii  disable escaping of non-ASCII characters
            --json-lines       parse input using the JSON Lines format. Use with --no-indent or --compact to produce valid JSON Lines output.
            --indent INDENT    separate items with newlines and use this number of spaces for indentation
            --tab              separate items with newlines and use tabs for indentation
            --no-indent        separate items with spaces rather than newlines
            --compact          suppress all whitespace separation (most compact)

I have linux/macos-agnostic bash functions in my dotfiles that unify this to “clip” and “paste” (since “copy” is too close semantically to “cp”)

I've aliased that (and its equivalents on Linux and Android/Termux) to 'xc' and 'xp' (for X11 Copy and X11 Paste, as I'd originated this on Linux).

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.

alias pbg='pbpaste | fgrep --color -i "`pbpaste -pboard find`"'

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.

  • TIL about named pasteboards https://developer.apple.com/documentation/appkit/nspasteboar...

    I recognize that your pbg alias works for pretty much any text you could copy, but I wanted to mention, in case you're looking at log files with plain old less, there's the & limiter, which limits the current view to only lines matching a regular expression (or, if you type ^R during a & prompt, for a text match).

    If you type ^N or ! during a & prompt it will limit the view to those lines that do not match the expression.

    These view limits stack, so you can "&WARN<enter>" to see all lines that have WARN in them, and then maybe you want to see just a certain PID so "&12345<enter>" and you'll only see lines with both WARN and 12345, but then that one module is printing out a bunch of messages you think are safe to ignore so you do "&!modulename<enter>" and it filters out log lines that match modulename. Very handy and less is everywhere.

I don't remember when I learned about these, but they've been game changers, and everyone I've shared them with feels the same way. I use your use case often as well, though through `jq` because I'm more familiar with it, and sometimes wish to do transforms.

  • You can use `python -m json.tool` for just JSON formatting, which is convenient now that Python is available by default in most Linux distros. Jq is really excellent though.

I have an alias that while trivally simple is quicker to type and remember. It copies whatever file you give it to the clipboard which is super handy. I use it with the "Compare with Clipboard" to diff a file in Rubymine for example.

alias clip='pbcopy <'

Those are so useful that I wrote trivial shell functions that do the same under Linux.

  • Since I'm bouncing between OSX and Linux a lot, I have a shell script with the same name on each that boils down to:

      if [ `uname` == "Darwin" ]; then
        pbcopy
      else
        xsel --clipboard
      fi

Where are you pasting the pretty json to view it?

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.

pb[paste|copy] are a life improver. Here is a one-liner to edit the pasteboard contents in vim.

  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