Terminal Life Hacks: pbcopy and pbpaste
Supercharge your terminal workflow with these Mac-native clipboard commands
I came across an interesting issue during an SSH session in my terminal a while ago. That was, I could not use ctrl+c and ctrl+v.
Why? Because in the terminal environment, ctrl+c serves a special purpose - it sends an interrupt signal to terminate running processes. This is actually a fundamental feature of Unix-like systems, where control characters are used to communicate directly with the system. When you press ctrl+c in your terminal, instead of copying text, you're actually telling your system "Stop what you're doing right now!"
I didn't want to use the mouse and go through the process of scrolling through a large page and copying the entire data, especially when working through large files. That's when I discovered pbcopy and pbpaste.
Let me share a real-world scenario where these commands become invaluable. Imagine you're debugging a production issue and need to compare configuration files between your local machine and the remote server. Traditionally, you'd need to:
SSH into the remote server
Open the config file
Manually select all text
Copy it
Create a local file
Paste the content
Instead, you can do this elegantly in just one line:
# SSH into remote server, get environment variables, and pipe directly to your local clipboard
$ ssh user@prod-server 'cat .env' | pbcopy
# Now you can paste it into a local file for comparison
$ pbpaste > .env.prod
These commands are particularly powerful when you're dealing with large files or need to copy specific portions of command output. The best part? They integrate seamlessly with other command-line tools through pipes, making them a natural fit for complex terminal operations.
# Example: Quickly save command output
# Instead of manually selecting and copying a long command output
$ ls -la | pbcopy
# Now the directory listing is in your clipboard, ready to paste anywhere
# Example: Working with config files
# Copy the contents of your SSH config for backup
$ cat ~/.ssh/config | pbcopy
$ pbpaste > ~/.ssh/config.backup
# Example: Extracting specific information
# Copy all error messages from a log file
$ grep "ERROR" application.log | pbcopy
Next time you find yourself reaching for the mouse to copy text in your terminal, remember these commands. They're simple, but they've saved me countless hours of manual copying and pasting. Sometimes the simplest tools make the biggest difference in our daily workflow.
Happy coding! ๐ฉ๐ปโ๐ป