Today I Learned

A Hashrocket project

235 posts about #command-line

Keeping an SSH connection alive

Do you get disconnected from your SSH session often? I do… but I’ve found a solution that helps.

An SSH configuration that can be made on the server or client side but in my instance it makes more sense for the update to be on the client side.

In your ~/.ssh/config we’ll utilize the ServerAliveInterval declaration.

ServerAliveInterval
             Sets a timeout interval in seconds after which if no data has
             been received from the server, ssh(1) will send a message through
             the encrypted channel to request a response from the server.  The
             default is 0, indicating that these messages will not be sent to
             the server.  This option applies to protocol version 2 only.

This declaration informs the client to send a keep alive packet at a certain interval to the server, ensuring the connection stays open.

Host example
  Hostname example.com
  ServerAliveInterval 30

That declaration will send a packet every 30 seconds if the connection goes idle. Now this is the desired funcationality that I’d like to see for all of my SSH connections so we can add it to the host wildcard like so:

Host *
  ServerAliveInterval 120

Tmux Kill All Other Sessions

Ok, you can kill a session in Tmux from the command line with tmux kill-session -t <session-name>. Did you know you can add a flag to kill every session other than your target? Here’s that command.

$ tmux kill-session -a -t <session-name>
$ tmux kill-session -at <session-name> # short version

All sessions but the target will die. This is my ‘clear the desk’ operation when I come back to my computer after some time away and want to shut down a bunch of random servers and processes.

Make dry run

make has an great option to validate the commands you want to run without executing them. For that just use --dry-run.

#!make
PHONY: test
test:
    echo "running something"

Then:

$ make test --dry-run
echo "running something"
$ make test
echo "running something"
running something

Thanks @DillonHafer for that tip!

Parallel xargs fails if any of its children do

We like to write about xargs. In addition to all that, turns out xargs is a great tool for easily parallelizing tests, linters or anything where some may pass, and some may fail. If any of the processes that xargs spawns fail, the xargs call will also fail.

All child processes exit zero:


% echo "0\n0\n0" | xargs -Icode -P4 sh -c 'exit code'; echo exit code: $?
exit code: 0

And so does xargs! If any exit non-zero:

echo "0\n1\n127" | xargs -Icode  -P4 sh -c 'exit code'; echo exit code: $?
exit code: 1

xargs follows suit.

Find File Case-Insensitively 🔎

When using the find command, consider the -iname flag. It works like -name:

True if the last component of the pathname being examined matches pattern.

But with case insensitivity:

-iname pattern
  Like -name, but the match is case insensitive.

Here’s a sample command, which will match utils.js and Utils.js.

$ find . -iname Utils.js

See man find for more information. h/t Raelyn.

Ack ignores node_modules by default

When searching through your JavaScript project it doesn’t make sense to search through your node_modules. But if your are on a spelunking journey into the depths of your dependencies, you may want to search through all your node_modules!

ack ignores node_modules by default, and ack being ack you can ack through ack to check it out:

> cat `which ack` | ack node_modules
--ignore-directory=is:node_modules

This is different behaviour from ag and rg which also ignore node_modules but not explicitly. They both ignore node_modules by ignoring all entries in the .gitignore file.

rg claims to implement full support for the .gitignore file while also claiming other search tools do not. The open issues list for ag bears that out.

With each of these tools, explicitly stating the directory to search through overrides the ignore.

> ack autoprefix node_modules
> rg autoprefix node_modules
> ag autoprefix node_modules

Delete a Command from ZSH history 📚

A while ago, I restored this site’s production database to a backup captured 24 hours earlier (the reason isn’t important). Now in my terminal history, heroku pg:backups:restore a719 DATABASE_URL -rproduction is just hanging out, ready for me to accidentally smash, sending our production database hurtling back into the past. How do I remove this destructive command from my history?

In my terminal, ZSH, there’s a file called ~/.zsh_history, and a similar one for Bash. To remove the command, open that file and remove the entry from the list.

cat somefile
heroku pg:backups:restore a719 DATABASE_URL -rproduction # delete me!
ls

Open a new terminal window, and the bad command is gone.

To avoid this situation, consider the following setting (thanks Dillon!):

# ~/.zshrc
setopt HIST_IGNORE_SPACE

With this, any command preceded by a space is excluded from history. One could alias a destructive command to itself, preceded by a space, and save themselves a headache. Note a weird bug here: the last command appears in history, even if it should be excluded, until another command is entered. Banish it to the ether by running just an empty space as a command.

asdf Global Versions 🌏

Spend a bit of time with asdf, and you might see an error like this:

$ npm install
asdf: No version set for command npm
you might want to add one of the following in your .tool-versions file:

nodejs 10.15.3
nodejs 8.9.1

The project I’m trying to set up via npm install doesn’t specify a Node version in .tool-versions, and since I have multiple Nodes on my machine, asdf isn’t sure which to use.

I don’t want to edit .tool-versions in this project; I’d rather asdf had a global default.

Here’s how I made that happen:

$ asdf global node 10.15.3   

How to clear a Mac terminal and its scroll-back?

Just type this: clear && printf '\e[3J'

Or even better create an alias for that, here’s mine:

alias clear='clear && printf "\e[3J"';

Here’s what I’ve learned today:

On Mac a regular clear is pretty much the same as typing Control + L on iTerm2. This clears the screen what’s good but sometimes I want to clear all the scroll-back to clean the noise and find things faster.

In order to clean the scroll-back I was performing a Command + K. This cleans the screen and the scroll-back. That’s great, except that it messes up with tmux rendering and tmux holds all the scroll-back per pane, so it won’t work at all.

So my new alias solves that as after clear the screen it also sends a terminal command to reset the scroll back through printf '\e[3J' and this keeps tmux working just fine!

Print Calendar With Week Number 📅

I use the week number (1-52) in my notetaking. How do I know what week number it is? ncal.

$ ncal -w
    May 2019
Mo     6 13 20 27
Tu     7 14 21 28
We  1  8 15 22 29
Th  2  9 16 23 30
Fr  3 10 17 24 31
Sa  4 11 18 25
Su  5 12 19 26
   18 19 20 21 22

Though not shown in the output above, today’s date (the 10th) is highlighted in my terminal output. At the bottom of the column containing today’s date is the week number (19).

Don't truncate when redirecting

A common problem in shell languages is truncating a file that you’re trying to transform by redirecting into it.

Let’s say I have a file full of “a”‘s

PROMPT> cat test.txt
aaaaaa

And I want to switch them all to “b”‘s

PROMPT> cat test.txt | tr 'a' 'b'
bbbbbb

But when I try to redirect into the same file I truncate file:

PROMPT> cat test.txt | tr 'a' 'b' > test.txt
PROMPT> cat test.txt
# nothing

This is because the shell truncates “test.txt” for redirection before cat reads the file.

An alternate approach is to use tee.

PROMPT> cat test.txt | tr 'a' 'b' | tee test.txt
bbbbbb
PROMPT> cat test.txt
bbbbbb

tee will write the output to both the file and to standard out, but will do so at the end of the pipe, after the cat command reads from the file.

Delete lines from file with sed

Imagine the following file:

sed.test

hised
hellosed
goodbyesed

If you want to delete a line matching a regular expression (e.g. hellosed), you can use d at the end of your regular expression.

sed '/hellosed/d' sed.test

Output:

hised
goodbyesed

However the file did not change:

cat sed.test

hised
hellosed
goodbyesed

To write the file in place use the -i [suffix] option. This argument allows you to specify the suffix of the backup file to be saved before committing your changes. For example:

sed -i '.bak' '/hellosed/d' sed.test

Now the file will be modified with our changes but we will also get a backup of the original file in sed.test.bak.

If you like living on the edge 🛩, and don’t want those pesky backup files littering your system, you can supply -i with an empty suffix, causing no backup file to be saved.

sed -i '' '/hellosed/d' sed.test

killall 💀

Today while pairing I learned about the killall command.

This BSD program kills processes by name, unlike kill, which uses PID.

Here’s me killing my Mac calculator:

$ ps aux | grep Calc
grep Calc
/Applications/Calculator.app/Contents/MacOS/Calculator
$ killall Calculator
$ ps aux | grep Calc
grep Calc

Thanks for the tip, Mark!

Two arguments in a command with xargs and bash -c

You can use substitution -I{} to put the argument into the middle of the command.

> echo "a\nb\nc\nd" | xargs -I{} echo {}!
a!
b!
c!
d!

I can use -L2 to provide exactly 2 arguments to the command:

> echo "a\nb\nc\nd" | xargs -I{} -L2 echo {}!
a b!
c d!

But I want to use two arguments, the first in one place, the next in another place:

> echo "a\nb\nc\nd" | xargs -I{} -L2 echo {}x{}!
a bxa b!
c dxa b!

I wanted axb! but got a bxa b!. In order to achieve this you have to pass arguments to a bash command.

> echo "a\nb\nc\nd" | xargs -L2 bash -c 'echo $0x$1!'
axb!
cxd!

Just like calling

bash -c 'echo $0x$1!' a b

Where $0 represents the first argument and $1 represents the second argument.

Parsing CSV at the command line with `csvcut`

Parsing csv at the command line is easy with the csvcut tool from csvkit.

csvkit is installable with pip

> pip install csvcut 

You can print only the columns you are interested in.

> echo "a,b,c,d" | csvcut -c 1,4
a,d
> echo "a,b,c,d" | csvcut -c 1,5
Column 5 is invalid. The last column is 'd' at index 4.

It also handles quoted csv columns:

echo 'a,"1,2,3,4",c,d' | csvcut -c 2,3

It handles new lines:

> echo 'a,b\nc,d' | csvcut -c 2
b
d

There are a virtual plethora of options check out csvcut --help.

csvkit has a number of csv processing tools, check them out here.

Get pip installed executables into the asdf path

Given I am using asdf when I install a python executable via pip, then I expect to be able to run that executable at the command line.

> asdf global python 3.7.2
> pip install some-executable-package
> some-executable
zsh: command not found: some-executable

This is because a shim has not yet been created for this executable. If you look into your shims dir for the executable:

> ls $(dirname $(which pip)) | grep some-executable

It doesn’t exist.

To place a shim into the shims dir of asdf you must reshim.

> asdf reshim python

And now you have a shim that points to the executable:

> ls $(dirname $(which pip)) | grep some-executable
some-executable
> some-executable
Hello World!

Confirming operations with `xargs -p`

xargs is a great tool to take a lot of input and execute a lot of different commands based on that input. Sometimes though, if you are performing destructive or mutative actions with xargs you want to proceed more cautiosly.

> echo "banana apple orange" | tr ' ' '\n' | xargs -n1 echo "I like"

This outputs:

I like banana
I like apple
I like orange

But maybe I don’t like some of those things, please ask! Including the p flag with xargs forces a prompt.

> echo "banana apple orange" | tr ' ' '\n' | xargs -p -n1 echo "I like"
echo I like banana ?...n
echo I like apple ?...y
I like apple
echo I like orange ?...n

Yep, I only like apples.

Get first image of animated gif

Image Magick’s convert tool has a no-option, very simple way to access the first frame of an animated gif.

convert 'animated.gif[0]' animated.first.gif

The square brackets after the file name above can contain any index for any frame of the image. 0 is the index of the first image.

To discover how many frames an animated gif has you can use:

identify animated.gif

Which will return a line for every frame in the animated gif. Those lines will look like this:

animated.gif[32] GIF 736x521 756x594+4+70 8-bit sRGB 256c 421707B 0.000u 0:00.000

Send Tmux Pane to Window

A scenario I find myself in frequently: I’ve started a server in a Tmux pane, and realize I don’t need to see the server logging in my ‘home’ Tmux pane (pane 0 for me).

To send a Tmux pane to its own window, use :break-pane.

A nice addition is the -n flag, which lets you set the new window name while breaking the pane.

:break-pane -n frontend-elm

Resize App Windows With AppleScript

I showed in a previous TIL how we can run AppleScript commands inline from the terminal. Here is an inline command for positioning and resizing your iTerm2 window.

osascript -e 'tell application "iTerm2"
  set the bounds of the first window to {50, 50, 1280, 720}
end tell'

The first two values tell the command the x and y coordinates of where to position the upper left corner of the window relative to the upper left corner of your screen. The next two values are the width and height that the window should be resized to.

source

Get Matching Filenames As Output From Grep

Standard use of the grep command outputs the lines that match the specified pattern. You can instead output just the names of the files where those matches occur. To do this, include the -l flag.

$ grep -Rl hashrocket .
./elixir/run-exunit-tests-in-a-deterministic-order.md
./git/show-file-diffs-when-viewing-git-log.md
./git/single-key-presses-in-interactive-mode.md
./internet/enable-keyboard-shortcuts-in-gmail.md
...

This recursive grep finds all the files where hashrocket appears. It only looks for the first match in a file, so each file will only be listed once even if there may have been multiple matches.

See man grep for more details.

Configure cd To Behave Like pushd In Zsh

The Zsh environment has a setting that allows you to make the cd command behave like the pushd command. Normally when you use cd the remembered directory stack is not effected. However, if you add the following setting to your ~/.zshrc file:

setopt auto_pushd

then using cd to navigate directories will cause those directories to be added to the dirs stack.

This is the default in the oh-my-zsh configuration of zsh.

List The Stack Of Remembered Directories

When you open a new Unix shell, you start in some directory, probably your home (~/) directory. If you use pushd to navigate to different directories, there is a paper trail of your movements, a listing of where you’ve been. You can view this listing of directories with the dirs command.

$ dirs
~/
$ pushd code
$ dirs
~/code ~/
$ pushd /usr/bin
$ dirs
/usr/bin ~/code ~/

Each time you pushd, the directory you have moved to is pushed onto the stack of visited directories. Alternatively, you can use the popd command to return to the previous directory, removing the current directory from the stack.

source

Parallel shell processing with xargs

Today I learned how to parallel run a slow command on my shell. We can use xargs combined with the flags -n and -P flags. Let’s see how this works:

find . -type f | xargs -n1 -P8 slow_command
  • slow_command your slow command that receives a file as the first arg
  • -n to specify how many arguments are passed to the slow_command
  • -P how many parallel workers xargs will spawn to run the slow_command

Check this out watch -d -n 0.1 "seq 10 | xargs -n2 -P8 echo":

watch-xargs

On this example xargs are spawning up to 8 workers to run the echo command and for each echo execution xargs will pass 2 arguments. The arguments are produced by a seq 10 and as multiple executions of echo runs in parallel we can highlight the output changes with watch.

Remotely control your desktop over SSH on macOS

Using SSH port forwarding and VNC you can connect to your remote desktop using the Screen Sharing application.

First connect to your machine over SSH and port forward 5900.

$ ssh user@machine.somehwere -L 5900:localhost:5900

Then in another terminal, on your local machine, open Screen Sharing by passing a open a VNC URL.

$ open 'vnc://localhost'

Screen Sharing should open and ask you for credentials for the remote machine. And then you do cool things on your remote desktop!

Read more about VNC here in this wikipedia article.

Hat Tip to Dorian Karter!

Capture and View screenshot on macOS remotely

First, wake up the desktop with caffeinate.

caffeinate -u -t 2 # assert that the user is active

Then switch to the application you want to have focus on the desktop with open

open -a Google\ Chrome

Then call MacOS’s screencapture command.

sudo screencapture /Users/dev/Desktop/FullScreen.png

Finally, if you are daring, using iTerm2, have downloaded imgcat from the iTerm imgcat site, have chmod +x that file, and have copied that file to /usr/local/bin, then view the captured image in your terminal with imgcat.

imgcat /Users/dev/Desktop/FullScreen.png

Delimiters for sed shell command

Today I learned that the sed shell command accepts other delimiters than /. I was trying to run the following:

folder="screens/components"
echo "~/FOLDER/index.js" | sed -e "s/FOLDER/${folder}/g"
# sed: 1: "s/{{folder}}/screens/co ...": bad flag in substitute command: 'c'

But I got a bad flag error. So I changed my delimiter to | and all works fine:

folder="screens/components"
echo "~/FOLDER/index.js" | sed -e "s|FOLDER|${folder}|g"

Quiet noisy ssh port forwarding errors

When you are connecting via ssh to another machine and portfowarding like:

ssh person@machine.name -L 8000:localhost:8000

And there is no server running on port 8000, then you might be getting errors like:

channel 2: open failed: connect failed: Connection refused

If this is the case, you can add the -q flag to your ssh command. The ssh man page documents -q as:

-q      Quiet mode.  Causes most warning and diagnostic messages to be

So the whole ssh command would look like:

ssh person@machine.name -L 8000:localhost:8000 -q

Hopefully this solves your problem!

H/T Brian Dunn

Pretty Print JSON responses from `curl` - Part 3

If you thought that the output was pretty enough from last TIL, you were wrong.

Dennis Carlsson tweeted me about a tool called bat that has automatically syntax highlighting for a bunch of different languages and can also display line numbers.

Just pipe bat after jq and you are good to go:

> curl 'https://til.hashrocket.com/api/developer_posts.json?username=gabrielreis' | jq  | bat

       │ STDIN
───────┼──────────────────────────────────────────────────────────────────────────────
   1   │ {
   2   │   "data": {
   3   │     "posts": [
   4   │       {
   5   │         "title": "Pretty Print JSON responses from `curl` - Part 2",
   6   │         "slug": "utpch45mba"
   7   │       },
   8   │       {
   9   │         "title": "Pretty Print JSON responses from `curl`",
  10   │         "slug": "pgyjvtuwba"
  11   │       },
  12   │       {
  13   │         "title": "Display line break content in React with just CSS",
  14   │         "slug": "mmzlajavna"
  15   │       }
  16   │     ]
  17   │   }
  18   │ }

If you know any other tricks on making stdout prettier I would love to learn them.

Pretty Print JSON responses from `curl` - Part 2

After posting my last TIL , Vinicius showed me another tool that goes beyond just pretty printing: jq

If you don’t pass any args to jq it will just pretty print same as json_pp:

> curl 'https://til.hashrocket.com/api/developer_posts.json?username=gabrielreis' | jq

{
  "data": {
    "posts": [
      {
        "title": "Pretty Print JSON responses from `curl`",
        "slug": "pgyjvtuwba"
      },
      {
        "title": "Display line break content in React with just CSS",
        "slug": "mmzlajavna"
      },
      {
        "title": "Mutations with the graphql-client Ruby gem",
        "slug": "xej7xtsnit"
      }
    ]
  }
}

What if you only want to display the first post on the response? Just pass an argument to filter the keys you want. It’s like Xpath for JSON: jq '.data.posts[0]'

> curl 'https://til.hashrocket.com/api/developer_posts.json?username=gabrielreis' | jq '.data.posts[0]'

{
  "title": "Pretty Print JSON responses from `curl`",
  "slug": "pgyjvtuwba"
}

See Part 3

Pretty Print JSON responses from `curl`

When you use curl to manually make API calls, sometimes the response is not formatted:

> curl 'https://til.hashrocket.com/api/developer_posts.json?username=gabrielreis'`

{"data":{"posts":[{"title":"Display line break content in React with just CSS","slug":"mmzlajavna"},{"title":"Mutations with the graphql-client Ruby gem","slug":"xej7xtsnit"},{"title":"The rest of keyword arguments 🍕","slug":"o2wiclcyjf"}]}}%

You can pipe json_pp at the end so you have a prettier json response:

> curl 'https://til.hashrocket.com/api/developer_posts.json?username=gabrielreis' | json_pp

{
   "data" : {
      "posts" : [
         {
            "slug" : "mmzlajavna",
            "title" : "Display line break content in React with just CSS"
         },
         {
            "title" : "Mutations with the graphql-client Ruby gem",
            "slug" : "xej7xtsnit"
         },
         {
            "title" : "The rest of keyword arguments 🍕",
            "slug" : "o2wiclcyjf"
         }
      ]
   }
}

See Part 2

Resize Tmux Pane 🖥

Sometimes, after a long day of coding, I resize a Tmux pane using my mouse instead of my keyboard. It’s a habit from my GUI-informed past.

Here’s how to accomplish this without a mouse.

To resize the focused pane left one cell (from the Tmux prompt):

:resize-pane -L

Resize pane number 3 right 10 cells:

:resize-pane -t 3 -R 10

Etc.

Change Prompt in Z Shell

When I live code, or share terminal commands in a demonstration, I don’t want my customized terminal prompt included in that information. It’s noisy.

Right now I’m changing this in Z Shell via that PROMPT variable.

# Complex prompt
jake@computer-name: echo $PROMPT
%{%}%n@%m%{%}:

# Simple prompt
jake@computer-name: PROMPT="$ "
$ echo 'ready to live code'
ready to live code
$

Pipe all output from a command (stderr & stdout)

When you write a bash/zsh script relying on pipes normally you will not be able to pipe through text from the stderr output with a normal pipe.

For example, curl -v prints some information about the request, including it’s headers and status into stderr.

If we simply try to pipe the output of curl -v into less we will not see the verbose header and request info:

curl -v https://hashrocket.com | less

Output:

<html lang='en-US'>
<meta charset='UTF-8'>
<title>Ruby on Rails, Elixir, React, mobile design and development | Hashrocket</title>
...

But if we want the stderr output as well we can use the |& syntax:

curl -v https://hashrocket.com |& less

Output:

* Rebuilt URL to: https://hashrocket.com/
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
...
* Connected to hashrocket.com (52.55.191.55) port 443 (#0)
...
<html lang='en-US'>
<meta charset='UTF-8'>
...

🍒 Bonus:

We can also pipe through ONLY the stderr:

curl -v https://hashrocket.com |1>& less

Output (will not contain the html response):

* Rebuilt URL to: https://hashrocket.com/
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
...

h/t Thomas Allen

Get ONLY PIDs for processes listening on a port

The lsof utility on Linux is useful among other things for checking which process is listening on a specific port.

If you need to kill all processes listening on a particular port, normally you would reach for something like awk '{ print $2 }', but that would fail to remove the PID column header, so you would also need to pipe through tail -1. It get pretty verbose for something that should be pretty simple.

Fortunatly, lsof provides a way to list all the pids without the PID header specifically so you can pipe the output to the kill command.

The -t flag removes everything from the output except the pids of the resulting processes from your query.

In this example I used a query to return all processes listening on port 3000 and return their PID:

lsof -ti tcp:3000

The output of which will look something like:

6540
6543
21715

This is perfect for piping into kill using xargs:

lsof -ti tcp:3000 | xargs kill

No awks or tails necessary! 🐕

Find The Process Using A Specific Port On Mac

The netstat utility is often recommended for finding the PID (process ID) bound to a specific port. Unfortunately, Mac’s version of netstat does not support the -p (process) flag. Instead, you’ll want to use the lsof utility.

$ sudo lsof -i tcp:4567

Running this will produce a nicely formatted response that tells you several pieces of information about the process bound to :4567 including the PID.

source

Grep For Files With Multiple Matches

The grep utility is a great way to find files that contain a certain pattern:

$ grep -r ".class-name" src/css/

This will recursively look through all the files in your css directory to find matches of .class-name.

Often times these kinds of searches can turn up too many results and you’ll want to pare it back by providing some additional context.

For instance, we may only want results where @media only screen also appears, but on a different line. To do this, we need to chain a series of greps together.

$ grep -rl "@media only screen" src/css |
    xargs grep -l ".class-name"

This will produce a list of filenames (hence the -l flag) that contain both a line with @media only screen and a line with .class-name.

If you need to, chain more grep commands on to narrow things down even farther.

See man grep for more details.