Useful Linux Examples

Eclectic collection of useful things in Linux

Run last command again with sudo

sudo !!

In the fish shell: Alt + s will prefix a command with sudo, so pair that with up-arrow to go back to last command

Working with Processes

Run my command in the background and intercept SIGHUP’s sent to the command

nohup my_command &

Let me exit this shell that owns the process identified by pid without sending SIGHUP to it

disown <pid>

Find existing process’s id

ps -ef | grep <substing of command>

Kill all the things (with a filter)

kill -9 `ps -aef | grep <substing of command> | awk '{print $2}'`

Environment variables

Set environment variables from .env file

export $(grep -v '^#' .env | xargs -d '\n')

Source (stackoverflow.com)

Fish
set -x ENV_VAR_NAME ENV_VAR_VALUE

Automation

Makefile’s are good for easily running developer environment setup, builds, and other repeatable tasks for a code base / repository. Additionally, it serves a great duel use as documentation on how to work with the project

SHELL := /bin/bash # Use bash syntax, by default uses /bin/sh
EXAMPLE ?= default # $EXAMPLE env var value if set else default
MAKEFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST)))
MAKEFILE_DIR := $(patsubst %/,%,$(dir $(MAKEFILE_PATH)))
.ONESHELL: # commands inside the same target run inside the same shell

.PHONY: thing1
thing1:
    echo "Thing 1"

.PHONY: thing2
thing2: thing1 # thing2 depends on thing1
    echo "Thing 2"
    echo "$(shell pwd)" # how to nest shell commands

Usage: make thing2

Bash to Fish conversion

Bash

$(...)

Fish

(...)

Git

How many commits do I need to rebase?

git rev-list --count HEAD ^origin/master

# if you merge other branches into yours, this will filter out the extra branches
git rev-list --count --first-parent HEAD ^origin/master

If you need to exclude merges you can use the --no-merges flag too

Useful packages

  • yadm - Yet Another Dotfile Manager, very useful for managing config settings of other applications, e.g. mine are here
  • fish - Better shell than bash, nice autocompletion
  • Starship - Terminal prompt useful for understanding context you are in
  • Alacritty - Good terminal emulator
  • tmux - Terminal Multiplexer
  • pyenv - Manage Python Environments
  • ripgrep - rg better grep

SSH

Add aliases for servers you connect to

.ssh/config

Host <alias>
    HostName <IP address / DNS>
    User <username>

ssh-copy-id - Copy ssh key to server, to avoid needing to type in password

Use your host’s SSH keys within a docker container

Dockerfile

docker run \
       --env SSH_AUTH_SOCK=/ssh-agent \
       --volume $SSH_AUTH_SOCK:/ssh-agent \
       ...

or equivalent docker-compose.yml

my-service:
    ...
    volumes:
        - $SSH_AUTH_SOCK:/ssh-agent
    environment:
        SSH_AUTH_SOCK=/ssh-agent

Continues here: “More-Useful-Linux-Examples”