Skip to content

Instantly share code, notes, and snippets.

@dodbrian
Last active June 5, 2022 21:40
Show Gist options
  • Save dodbrian/3c6cb88244cbbb95fda6d78acf82c7ee to your computer and use it in GitHub Desktop.
Save dodbrian/3c6cb88244cbbb95fda6d78acf82c7ee to your computer and use it in GitHub Desktop.
Linux Commands

Linux CLI Commands

Filesystem Hierarchy Standard

https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard

Setting up SSH key-based authentication

# Generate a key pair for the client (local) machine
$ ssh-keygen -t rsa

# Transfer the key to a remote machine
$ ssh-copy-id remote-machine

# Transfer the key using a jump host
$ ssh-copy-id -o ProxyJump=user@jumphost user@targethost

Adding existing key to SSH

ssh-add path-to-key/key-name.pem

Enabling AgentForwarding

# agent forwarding lets you authenticate with the same key 
# you used to log in to the bastion host for further SSH 
# logins initiated from the bastion host.
# Agent forwarding is a potential security risk, 
# because the bastion host is able to read the private key from 
# your computer.
ssh -A user@remote-machine

SSH jump host

# You can use the -J option to jump through a host
ssh -J user1@host1:port1 user2@host2:port2

# The same syntax can be used to make jumps over multiple machines
ssh -J user1@host1:port1,user2@host2:port2 user3@host3

Package management

Package sources

cd /etc/apt
less sources.list

Display packages update log

grep "2017-08-21" /var/log/dpkg.log | grep "status installed"

Boot

less /etc/default/grub

Runlevels

systemctl enable multi-user.target

Parsing a data stream

cut -d: -f3 /etc/group
cut -d: -f3 /etc/group | sort -n
cut -d: -f3 /etc/group | sort -rn

Using command substitution

cd /lib/modules/`uname -r`/kernel

Writing a file from standard error

wget pluralsight.com 2> errorfile.txt

Locale management

locale
localectl status
localectl list-locales

Time and Date

timedatectl
timedatectl list-timezones
timedatectl set-timezones

Variables

myval=5
echo $myval
export myval

Bash History

history

Bash Prompt

# Sets up bash prompt with Git branch information
export GIT_PS1_SHOWDIRTYSTATE=true
export GIT_PS1_SHOWUNTRACKEDFILES=true
export PS1='\n\e[1m\[\033[38;5;10m\]\u@\h\e[0m:\e[1m\[\033[38;5;4m\]\w\[\033[38;5;13m\]$(__git_ps1)\e[0m\n$ '

Information about a Linux command

type
type wget
info wget  # info document for a command
man wget

Processes

systemctl 

Keyboard

Set up Ctrl+Alt act like Alt gr

# install xbindkeys and xvkbd
sudo apt-get install xbindkeys xvkbd

# create configuration file
nano ~/.xbindkeysrc

Add the following configuration for the key mapping:

"xvkbd -xsendevent -text '{'"
    m:0xc + c:16
    Control+Alt + 7

"xvkbd -xsendevent -text '['"
    m:0xc + c:17
    Control+Alt + 8

"xvkbd -xsendevent -text ']'"
    m:0xc + c:18
    Control+Alt + 9

"xvkbd -xsendevent -text '}'"
    m:0xc + c:19
    Control+Alt + 0

"xvkbd -xsendevent -text '\[backslash]'"
    m:0xc + c:20
    Control+Alt + ssharp

"xvkbd -xsendevent -text '\[asciitilde]'"
    m:0xc + c:35
    Control+Alt + plus

"xvkbd -xsendevent -text '\[asciicircum]'"
    m:0xc + c:48
    Control+Alt + ä

"xvkbd -xsendevent -text '\[at]'"
    m:0xc + c:24
    Control+Alt + q

"xvkbd -xsendevent -text '\[bar]'"
    m:0xc + c:94
    Control+Alt + <
# then reload xbindkeys
xbindkeys -f ~/.xbindkeysrc

In oder to add other characters, xev command can be used to find out the keycode. In the following command output the keycode 24 corresponds to the character @:

KeyRelease event, serial 61, synthetic NO, window 0x5a00001,
    root 0x12f, subw 0x0, time 3989393, (650,933), root:(769,1072),
    state 0x90, keycode 24 (keysym 0x40, at), same_screen YES,
    XLookupString gives 1 bytes: (40) "@"
    XFilterEvent returns: False

Compose Key Sequences

Applications using Xlib input handling should recognize these compose key sequences in locales using the iso8859-14 compose table.

Network management

Hostname

hostnamectl set-hostname myhostname

Interfaces

# displays a list of available interfaces
sudo lshw -C network | grep logical

# display a list of available interfaces using NetworkManager
$ networkctl list
IDX LINK            TYPE     OPERATIONAL SETUP
  1 lo              loopback n/a         unmanaged
  2 enp0s25         ether    n/a         unmanaged
  3 wlp2s0          wlan     n/a         unmanaged
  4 wlxd0374517f383 wlan     n/a         unmanaged
  5 docker0         bridge   n/a         unmanaged
  7 vethbd8e085     ether    n/a         unmanaged

6 links listed.

# display current IP addresses configuration
$ networkctl status 
WARNING: systemd-networkd is not running, output will be incomplete.

●   State: n/a
  Address: 192.168.178.21 on wlxd0374517f383
           172.17.0.1 on docker0
           fd00::90e1:921f:c8cb:6b2a on wlxd0374517f383
           fd00::d5ce:19a9:3cb1:dfca on wlxd0374517f383
           fe80::a3fd:5c1a:9680:5cee on wlxd0374517f383
           fe80::42:80ff:febe:b6b2 on docker0
           fe80::58d1:7bff:fe05:a2bb on vethbd8e085
  Gateway: 192.168.178.1 (AVM Audiovisuelles Marketing und Computersysteme GmbH) on wlxd0374517f383
ip link set eth0 up		# enable eth0 interface
ip link set eth0 down	# disable eth0 interface

Permanently disable interface (Network Manager)

Add a file in /etc/NetworkManager/conf.d called, for example local-ignore-wlp2s0.conf, with the following content:

[keyfile]
unmanaged-devices=interface-name:wlp2s0

Netplan

Netplan configuration is located in /etc/netplan

netplan generate		# generate network config from yaml files
netplan try				# try to apply configuration

netplan apply			# apply network configuration
netplan --debug apply

Sample netplan configuration file:

network:
  version: 2
  renderer: networkd	# can be omitted
  ethernets:
    eth0:
      dhcp4: false
      addresses:
        - 172.16.0.1/12
      gateway4: 192.168.178.1
      nameservers:
        addresses: [192.168.178.1]

DNS lookup utilities

$ dig some.web.host

$ nslookup some.web.host

DNS configuration

# display DNS status
$ resolvctl status

Dynamic file for connecting local clients to the internal DNS stub resolver of systemd-resolved is located at /etc/resolv.conf.

IP Forwarding

# Check if IP forwarding is enabled
$ sysctl net.ipv4.ip_forward

# or
$ cat /proc/sys/net/ipv4/ip_forward

# Enable IP forwarding on the fly
$ sysctl -w net.ipv4.ip_forward=1

# or
$ echo 1 > /proc/sys/net/ipv4/ip_forward

# Make this configuration permanent
# /etc/sysctl.conf:
net.ipv4.ip_forward = 1

# Enable the changes made in sysctl.conf
$ sysctl -p /etc/sysctl.conf

# Restart network service on RedHat based systems:
$ service network restart

# and on Debian/Ubuntu systems:
$ /etc/init.d/procps.sh restart

Enable NAT

$ sudo iptables --table nat --append POSTROUTING --out-interface wlan0 -j MASQUERADE

Persist firewall rules

# save IPv4 rules manually
$ sudo /sbin/iptables-save > /etc/iptables/rules.v4

# restore IPv4 rules manually
$ sudo /sbin/iptables-restore > /etc/iptables/rules.v4

# save IPv6 rules manually
$ sudo /sbin/ip6tables-save > /etc/iptables/rules.v6

# restore IPv6 rules manually
$ sudo /sbin/ip6tables-restore > /etc/iptables/rules.v6

Enable automatic firewall rules reloading

# Install iptables-persistent package. During the installation you'll be asked to save firewall rules.
$ sudo apt install iptables-persistent

Disk Management

Disk Space Usage

df -ht ext4

List Block Devices

lsblk | grep sd

Mouning Devices

mkdir /media/newplace
mount /dev/sda1 /media/newplace
umount /media/newplace

Mount ISO/IMG file

# Add partitions from image file to loop-devices
sudo partx -av image.img

# List created loop-devices
losetup

# Mount added devices
sudo mount /dev/loop1 ./mnt_point

# Remove partitions after unmounting
sudo partx -dv /dev/loop1

# Remove no longer used loop-devices
sudo losetup -d /dev/loop1

Create full disk image

sudo dd bs=4M if=/dev/sdb of=/home/denis/usb.img status=progress

Write image to disk

sudo dd bs=4M if=/home/denis/usb.img of=/dev/sdb status=progress

ddrescue can also be used instead of dd.

Create sparse disk image

# Determine the size of the image. It should be a total of the size of all partitions, except for the last one. Only the size of the used space of the last partition needs to be used.
sudo partx --show /dev/mmcblk0

# Copy the contents of the drive to the files having maximum size specified with the `count` number calculated using the information from the previous step.
sudo dd if=/dev/mmcblk0 of=/home/denis/image.img bs=8M count=512 status=progress

# Change the owner of the file if needed
sudo chown $USER image.img

Check and fix a disk

sudo fsck.ext4 -pfvy /dev/sda1
sudo fsck.vfat -pfvy /dev/sda2

Format disk

$ sudo mkfs.vfat /dev/sdb1
$ sudo mkfs.ntfs /dev/sdb1
$ sudo mkfs.exfat /dev/sdb1

File Management

Remove file extension

# removes *.tif extension
for i in ./*.tif; do mv -i "$i" "${i%.tif}"; done

Truncate file size

truncate -s 10G foo.bar

Display File Mode in Octal Format

$ stat -c "%a %n" ./Documents/Udev.html 
664 ./Documents/Udev.html

Examine Kernel ring buffer

dmesg

List Hardware

lshw

Graphic Devices

# Show Graphic card(s) information, including details of card and card driver, display protocol (if available), display server (and/or Wayland compositor), vendor and version number
inxi -G

# show information about the GLX implementation
glxinfo |grep -Ei 'opengl|direct rendering'

GPU Utilization

# Display a top-like summary of Intel GPU usage
intel_gpu_top

Desktop Environment

KDE Application Menu Locations

  • /home/username/.config/menus/applications-kmenuedit.menu
  • /home/username/.local/share/applications/app-name.desktop

Linux Containers

Linux containers project

apt install lxd
lxd init
lxc launch images:centos/8/amd64 centos8
lxc exec centos8 /bin/bash

Misc

# print newline, word, and byte counts for each file
apt list --all-versions | wc
# executes commands at a specified time
poweroff | at now + 5 minutes
# formats JSON output of a pipe command
aws ec2 describe-instances | jq

Raspberry Pi

Prevent from rebooting after powering off

In /boot/firmware/usercfg.txt add:

dtoverlay=gpio-poweroff

Scripting

Working with user inputs

#!/bin/bash
declare -i number1
declare -i number2
declare -i total
echo "What's your favorite number? "
	read number1
echo "What number do you really hate? "
	read number2
total=$number1*$number2
	echo "Aha! They equal " $total
exit 0

Looping with for

#!/bin/bash
for i in {0..10..2}
  do
     echo "We've been through this $i times already!"
  done
#!/bin/bash
for filename in file1 file2 file3
  do
	echo "Important stuff" >> $filename
  done

if-else controls

#!/bin/bash
echo "What's your favorite color? "
read text1
echo "What's your best friend's favorite color? "
read text2
	if test $text1 != $text2; then
		echo "I guess opposites attract."
	else
		echo "You two do think alike!"
	fi
exit 0

Counting with while

#!/bin/bash
declare -i counter
counter=10
	while [ $counter -gt 2 ]; do
		echo The counter is $counter
		counter=counter-1
	done
exit 0

Testing input using case

#!/bin/bash
echo "What's tomorrow's weather going to be like?"
read weather
	case $weather in
		sunny | warm ) echo "Nice! I love it when it's " $weather
		;;
		cloudy | cool ) echo "Not bad..." $weather" is ok, too"
		;;
		rainy | cold ) echo "Yuk!" $weather" weather is depressing"
		;;
		* ) echo "Sorry, I’m not familiar with that weather system."
		;;
	esac
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment