zs3.me

Useful Linux Command-Line Tips

Revision 69
© 2020-2026 by Zack Smith. All rights reserved.

Hardware identification

Print a near-complete inventory of your Linux system's hardware

  • inxi -Faz
  • hwinfo
  • hw-probe

Print the CPU type or chip name

  • lscpu
  • uname -m (print machine e.g. aarch64)
  • uname -p (print processor)
  • grep Hardware /proc/cpuinfo (print SoC's name etc.)

Print the number of processors

  • nproc

Print the CPU cache sizes

  • getconf -a | grep CACHE_SIZE

Print the device model

  • grep Model /proc/cpuinfo
  • cat /sys/firmware/devicetree/base/model; echo
  • cat /proc/device-tree/model; echo

Print bus information

  • lsusb -v | less
  • lspci -v

Storage Tips

List all connected drives

The easiest way to list all drives:

  • lsblk

Or, if you can get a similar result thus:

  • sudo fdisk -l

Benchmark disk read speed

Given a drive that is ideally not mounted or in use, you can estimate its read speed thus:

 sudo hdparm -t /dev/sdX

Benchmark disk write speed

 dd if=/dev/zero of=filler.dat status=progress

Get fine details about a drive

Many details:

 udevadm info --query=all --name=/dev/sd

Fewer details:

 sudo hdparm -I /dev/sdX

Set the partition table of a drive to GPT

This is useful if any partition needs to be larger than 2 TB.

 sudo parted /dev/sdX mklabel gpt

View the logical sector size of a drive

This is a useful BASH function to show more details about a drive such as the logical sector size.

 function blk {
  lsblk -o NAME,PHY-SEC,LOG-SEC,SIZE,MODEL,MOUNTPOINT
 }

You can also do:

 sudo fdisk -l /dev/sdX

Refresh a flash drive's data

Over time, flash memory cells lose their charge and therefore their data unless they are refreshed. To refresh them, you have to read and write back every block on the drive. Manufacturers aren't going to tell you this detail. If you have important data on a thumb drive or SSD, you need to refresh the drive.

To read and write back every block on a drive, i.e. rewrite the entire disk sector by sector, you can use the dd command:

 sudo dd if=/dev/sdX of=/dev/sdX bs=1M status=progress

How to mount a disk image img file

  1. Use fdisk diskImage.img to find the starting sector of the partition that you want to mount.
  2. Then sudo mount -t ext4 -o loop,offset=$((start*512)) diskImage.img /mnt

How to mount an ISO file

  • sudo mount -o loop DVDROM.iso /mnt

How to erase a DVD±RW disc, fill it with random bytes:

 function wipe_dvd {
  dvd+rw-format -force /dev/sr0
  growisofs -dvd-compat -overburn -Z /dev/sr0=/dev/random
 }

How to erase a CD-RW disc

 function wipe_cd {
  cdrdao blank --blank-mode full
  cdrecord /dev/random
 }

Create a RAM disk

  • sudo mount -t tmpfs -o size=4000M,mode=1777 myRAMdisk /mnt

Why use a RAM disk?

  1. It's the fastest possible drive.
  2. Using a RAM disk avoids wear and tear on physical drives (whether solid state drives or spinning hard disks).
  3. It operates separately from physical drives, therefore doesn't slow down access to them.
  4. A RAM disk is fine for temporary operations where it is OK to discard the result after reboot.

If you had the forethought to buy oodles of RAM with your system, e.g. 32 or 64GB, you can always have a RAM disk on hand and avoid the relative slowness of an SSD.

Eject and power down an external drive

  • sudo umount /dev/sdX[1-9]
  • sudo eject /dev/sdX
  • sudo udisksctl power-off -b /dev/sdX

 function Eject {
  if sudo umount $1[1-9]; then
   if sudo eject $1; then
    if sudo udisksctl power-off -b $1; then
     echo Success
    else
     echo Failed to power down
    fi
   else
    echo Failed to eject
   fi
  else
   echo Failed to unmount
  fi
 }
 # e.g. Eject /dev/sda

Check a drive's health

 smartctl -H /dev/sdX

This only works if the drive has SMART support. To install smartctl do sudo apt install smartmontools.

Or if you prefer a GUI, install and run gsmartcontrol.

How to list all current open files for a particular program

  • lsof -c program-name

 Example:
 lsof -c firefox-esr | grep mozilla

Set the name (volume label) of an EXT4 drive

You can use this:

  • sudo e2label /dev/sdX MyLabel

Or this:

  • sudo tune2fs -L MyLabel /dev/sdaX

If it's an encrypted volume you'll use a path like

 /dev/mapper/driveX

Set the volume label of a FAT drive

 dosfslabel /dev/sdX MyLabel

How to identify high-bandwidth file I/O (fully manual approach)

Up in the /proc directory there are subdirectories for every running process. In these, there is an io file that has tallies for I/O operations. You can only access these files as root, but if you do, you can find out what the most aggressive process is, in term of I/O.

Find the most writes:

  sudo grep write_bytes /proc/[0-9]*/io | sort -k 2 -n

The sort operation sorts by the second field which is the number of bytes written, and sorts numerically instead by ASCII.

How to identify high-bandwidth file I/O (automatic approach)

While you can always get a list of open files using lsof, that doesn't tell you which files are being used the most.

If you want to know which files are the focus of the most I/O activity, the following command is crucial.

  • sudo iotop

This program was useful to me when a badly written program (pcmanfm) began filling up my drive rapidly, writing 100 MB per second of log messages.

You can reduce the update duration of iotop using the -d option.

List all video files

 function l4 {
  while read filename; do
   extn=${filename##*.}
   extn=${extn,,}
   case $extn in
    mp4 | mkv | avi | webm | part \
    mpeg | mpg | mov | m4v )
     size=$( ls -lh "$filename" | cut -d ' ' -f 5 )
     echo "$size $filename" # use Tab
     ;;
   esac
    done <<< $(ls)
 }

Notice that the use of while read and 'done <<<' are needed to preserve spaces within paths. If you use foreach file in then you may see that BASH breaks up paths that contain spaces into meaningless partial paths.

Networking Tips

Print your network card's MAC address.

Replace wlp3s0 with the name of your adapter:

 cat /sys/class/net/wlp3s0/address

How to list all current TCP and UDP network connections

 netstat -e -t -u -W -p -4 -6 2> /dev/null \
   | sed 's/ [ ]*/ /g' \
   | awk '{ printf("%s %s\n", $9, $5); }' \
   | sort \
   | grep -e '^[0-9]' -e ^-

List all network connections of a program

  • lsof -c program -i TCP -i UDP -a

 Example:
 lsof -c firefox-esr -i TCP -i UDP -a

List all programs listening on TDP and UDP ports

  • netstat -ltup

List running network totals per process

  • sudo nethogs -t -d 1

Show live network totals per process

  • sudo iftop

Print your machine's IP address

 hostname -I
 hostname --all-ip-addresses

Unfortunately if there are none, a blank line will be printed and the return value is zero (success).

Therefore, grep '[0-9]' in order to get a return value of 0 for present and nonzero for missing.

Identify machines on your network

First confirm that your IP address is 192.168.*, 10.10.*.* or whatever.

  • sudo arp-scan -xq 192.168.1.0/24
  • nmap -sn 192.168.1.0/24
  • arp

Change your DNS server

  1. Edit /etc/resolvconf.conf
  2. You will change the line name_servers=
  3. Add a reliable server e.g.
    1. 1.1.1.1 (cloudflare)
    2. 9.9.9.9
  4. For example name_servers="1.1.1.1 9.9.9.9"

Print your DNS server

  • dig | grep SERVER

Perform DNS lookup

  • dig domainname
  • nslookup domainname

If not installed, these are found in the package dnsutils.

Print all adapters up/down status

 function nets {
  pushd /sys/class/net > /dev/null
  for s in *; do
   if [[ "$s" != lo ]]; then
    echo $s: `cat $s/operstate`
   fi
  done
  popd > /dev/null
 }

Get up/down status of Ethernet

  • sudo ethtool eth0

Get driver info for Ethernet adapter

  • sudo ethtool -i eth0

Get network adapter status

This prints the UP/DOWN status and any IP addresses.

  • ip a s eth0

How to block DNS lookup of a domain

Once upon a time, merely adding 0.0.0.0 twitter.com to your /etc/hosts file was enough to prevent a web browser from going to that site unless the user has hand-entered the IP address.

These days however, some browsers are ignoring the /etc/hosts file, such as when they have DNS-over-HTTPS enabled.

  • Text-based browsers Lynx and Links are still influenced by /etc/hosts.
  • Firefox 78 with DoH enabled ignores it. The latest Firefox however should fix this issue and respect /etc/hosts.
  • Chromium appears to ignore /etc/hosts.

How to block outgoing traffic to a domain with your firewall

  1. Use ping to get the IP address for a domain's web server.
  2. Use whois to get CIDR IP range(s) for that server.
  3. Add a firewall rule to block outgoing traffic to the IP range(s).

Some big websites have hundreds servers at various domains and subdomains, and they will redirect your browser to whichever of them is closest to you depending on your current location. Therefore you might want to start with the main domain.

Example of blocking a Facebook server:

1. Get the server IP

ping facebook.com identifies the server 157.240.22.35

2. Get the server IP range

whois 157.240.22.35 gets you the IP range in CIDR format: 157.240.0.0/16

3. Block

To block using ufw:

 sudo ufw deny out proto tcp from any to 157.240.0.0/16

If you use iptables directly rather than via ufw, it would be more like this:

 iptables -A OUTPUT -d 157.240.0.0/16 -p tcp --dport 443 -j REJECT
 iptables -A OUTPUT -d 157.240.0.0/16 -p tcp --dport 80 -j REJECT

How to get the SHA-1 HTTPS fingerprint of a site

 function fp {
  openssl s_client -connect $1:443 < /dev/null 2>/dev/null |\
       openssl x509 -fingerprint -noout -in /dev/stdin
 }

USB Tips

Print USB devices

  • lsusb [-v]

Enable a printer that was mysteriously stopped

  1. Get the precise printer name with lpq
  2. sudo cupsenable printerName

Scan a page using an HP printer

  • hp-scan -mcolor

Check your HP printer ink levels

  • hp-levels

Scan for printers

  • nmap -p 9100,515,631 192.168.0.1/24

Fetch all photos and video files from your Android device

You'll need to install Android Debug Bridge.

  • sudo apt install adb

Then you can just grab all the photos and screenshots. On Android, alternative camera apps also store their data

  • adb pull /sdcard/DCIM

Fetch all photos and video files from your USB-connected camera or phone

I find this is more convenient than taking out the SD card, putting it in the laptop, clicking on the card icon, and finding the DCIM folder to drag and drop.

 function getphotos {
  gphoto2 --auto-detect -P
 }

This works with cameras, Android phones and possibly iPhones. You may need to tap an Allow or Trust button on the device.

Display, Video and Graphics Tips

Print X display information

 xwininfo -root | grep -e Width -e Height -e Depth

Print Intel display information

 sudo cat /sys/kernel/debug/dri/0/i915_display_info

Take a screenshot from the command line

Two ways to capture the entire screen, the first one if faster:

  • scrot -z
  • xwd -out a.xwd -silent -root

Make a screen recording

  • simplescreenrecorder: this utility requires specifying coordinates to record an area.
  • kazam: this utility lets you easily select an area to record with your mouse.

Change the screen brightness

Set it to 10%:

  • brightnessctl s 10

Change the screen color temperature

Set it to 3333K, perfect for late night:

  • xsct 3333

Configure the Linux desktop for Dark mode

  • In Settings/Appearance, choose a dark GTK theme e.g. Adwaita-dark.
  • In Settings/QT5, choose either a dark theme or tell it to mimic GTK2.
  • In Firefox, install Mozilla's dark theme.
  • To run xpdf in inverted mode, run it with the -rv option.

If you don't see a way to select the GTK theme, you can edit the file ~/.config/gtk-3.0/settings.ini

Configure the Linux desktop for high-DPI (e.g. Retina) mode

If you bought a computer with a high-DPI display (4K, etc.), this customization may save your eyesight.

Xfce appearance

  • If you are using Xfce, you merely need to go into Settings/Appearance, click the Fonts tab and set the DPI. This will cover most cases.
    • The top panel: You may need to increase its height to accommodate the larger font.
  • Some GTK applications invoked via command line may require that you add the following to your ~/.bashrc file, where 2 is a scale factor:
    • export GTK_CSD=2

Enabling Xfce

If you're using a distro that doesn't have Xfce, you can switch to it by selecting it in some settings that are reachable via the command-line.

  • sudo update-alternatives --config x-session-manager
    • Typically choose startxfce4.
  • sudo update-alternatives --config x-window-manager
    • Typically choose xfwm4.
  • Edit the login screen, either of these:
    • sudo vi /etc/lightdm/lightdm.conf
    • sudo vi /usr/share/lightdm/lightdm.conf.d/01_debian.conf

Raspberry Pi OS

Rpi OS has a built-in DPI setting analogous to Xfce's. Go to the main menu and select Preferences/Appearance Settings. In the configuration window, select Defaults. There are 3 DPI options:

  1. large screens
  2. medium screens (1080p)
  3. small screens

Configure a high-DPI monitor for a lower resolution

If you are running Raspberry Pi OS and 4k mode feels sluggish, you can use pixel doubling to send 1080p to the monitor for a more responsive display experience. Go to the main menu and select Preferences/ScreenConfiguration. There, select the monitor and a reduced resolution.

Set your video card's output brightness

If your video card supports setting the output brightness (not all do: the Raspberry Pi 4's does not) this may help in the event that you are connected to an overly bright monitor or TV.

 function brightness {
  xrandr -s 0 --output HDMI1 --brightness $1
 }

Change the output device to whatever your system needs.

If this does not work

Check your monitor's built-in settings to see if you can set a custom color temperature wherein you specify the percentage of each of red, green and blue channels. If such a setting exists, set all of them to a lower percentage e.g. 50%.

Lock the screen from the command line

In the olden days, you would just use xlock.

Today on Debian, you can do:

  • dm-tool lock
  • xtrlock -b

Browser Tips

Firefox UI dark mode

Firefox now offers a Dark theme. In the menu, go to Edit, Preferences, Extensions and Themes. This only affects the app's UI, not the web content.

Firefox web content dark mode

If a web page supports dark mode but isn't displaying as dark, set the following in about:config ...

  • browser.in-content.dark-mode = true
  • ui.systemUsesDarkTheme = true
  • prefers-color-scheme = dark
  • privacy.resistFingerprinting = false

Note, in some versions of Firefox built-in dark mode is broken.

If a web page does not support dark mode, or Firefox isn't supporting it correctly, you can force it using my Javascript code here.

Package managers

APT

Print all installed packages

  • dpkg -l
  • apt list | grep installed

List all files in an installed package

Install the apt-file utility:

 sudo apt install apt-file
 sudo apt-file update

Then you can list a package's files:

 apt-file list gcc-aarch64-linux-gnu

Clean up apt's cache bloat

 sudo apt clean

RPM

Show files in an RPM

 rpm -ql file.rpm

BASH Tips

Redirect stderr to a file

 command 2> file
 e.g. command 2> /dev/null

Redirect stderr to stdout

 command 2>&1

Convert a string to lower case

 string="THIS IS A STRING"
 echo ${string,,}

This prints this is a string.

If you are using zsh instead of bash, you do this instead:

 echo ${(L)string}

Convert a string to upper case

 string="This is a string"
 echo ${string^^}

This prints THIS IS A STRING.

If you are using zsh instead of bash, you do this:

 echo ${(U)string}

Detect whether a string begins with some prefix

 if [[ "the_string" == prefix* ]]; then
  echo It does.
 fi

Note that prefix* must not be in quotes.

Detect whether a string begins with some suffix

 if [[ "myfile.mp4" == *mp4 ]]; then
  echo It does.
 fi

Note that suffix must not be in quotes.

Remove the extension from a filename

 filename=xyz.jpg
 base=${filename%.*}

Extract just the extension of a filename or file path

 path="/home/me/Photo.tiff"
 echo ${path##*.}

This prints tiff.

Extract just the filename of path

 path="/home/me/Photo.tiff"
 basename $path

This prints Photo.tiff.

Concatenate multiple lines of text

 tr '\n' ' ' < lines.txt > singleLine.txt

The resulting file singleLine.txt will not have any newlines.

Loop within a range of numbers

 for n in {1..1000}; do
  echo $n
 done

Generate a random number from 0...n

 n=255
 echo $(($RANDOM % $n))

Generate a random password

 date | sed s/^/$RANDOM/ | shasum

Find all occurrences of a string only within text files

 # grep recursively all text files
 function grat {
  nice find . -name '*.txt' -exec grep "$1" {} \; 2> /dev/null
 }

Find all occurrences of a string only within C/C++ header files, case insensitive

 # grep recursively all, case insentitive header files
 function graih {
  nice find . -name '*.h' -exec grep -i "$1" {} \;
 }

Extract the nth line of a text file

 tail -n +LINENO file | head -1

Array usage

 # Defintion
 A=(1 2 3 4 5)
 # Append an element
 A+=( 6 )
 # Access an element
 echo ${A[2]}
 # Delete an element
 unset ${A[3]}
 # Print all elements
 echo ${A[*]}
 # Loop through elements
 for i in ${A[@]} ; do ... done

How to open a file according to its extension

Whereas on the Mac there is a universal open command, on Linux the situation is a bit more dicey.

Yes, there is xdg-open, but whether it opens the correct program depends on whether you have mastered its arcane mechanism for specifying associations between file types and programs.

Neither open nor xdg-open differentiates between different actions e.g.

  1. display image file
  2. edit image file

Or

  1. play audio file.
  2. edit audio file.

I created BASH functions for each type of operation, such as this one for opening a file:

 # Open
 function o {
  if [ -d "$1" ]; then
   Thunar "$1" # Open directory
  else
   file="$1"
   extn=${1##*.}
   extn=${extn,,}
   case "$extn" in
    bmp | heic | jpg | png | gif | jpeg | tif | tiff )
     geeqie "$file"
     ;;
    raf | crw | dng )
     rawtherapie "$file"
     ;;
    mp4 | mkv | webm | avi | m4v | mpg | mpeg )
     mplayer "$file"
     ;;
    mp3 | wav | au | m4a )
     ffplay "$file"
     ;;
    pdf | ps )
     xpdf -rv -z width "$file"
     ;;
    html | htm )
     firefox "$file"
     ;;
    *)
     echo Unsure.
     ;;
   esac
  fi
 }

Files

Print the file type based on header

  • file filepath

Sample output: fubar.o fubar.o: ELF 64-bit LSB relocatable, ARM aarch64, version 1 (SYSV), stripped

Print the symbols in an executable or object file

  • nm fubar.o
  • nm executablefile

Strip the symbols from an executable or object file

  • strip fubar.o
  • strip executablefile

Print all ASCII strings in a binary file

  • strings fubar.o
  • strings executablefile

Continuously print new lines appearing at the end of a log file

  • sudo tail -f /var/log/messages

Print metadata about a media file

  • ffprobe video.mp4

Print the date a DNG photo was taken

  • magick identify -verbose file.dng | grep dng:create.date

Print a binary file in hexadecimal form

  • od -x file

Print a binary file in hex and ASCII forms

  • od -a -x file

Unzip to stdout (standard output)

  • unzip -p input.zip myfile.pdf > outputfile

Find a file based on its inode number

You may have noticed that fsck.ext4 will occasionally print warnings about files, giving only the inode number. How to learn what file that refers to? It's easy:

 sudo find / -inum 123456

Delete files less than a certain size

This is useful when a script fails and produces a bunch of empty output files.

 find dirPath -name '*.foo' -size -10k -delete

Delete files greater than a certain size

This could be useful when a script produces enormous log files.

 find dirPath -name '*.log' +size +100M -delete

Copy a file and see the transfer rate

First approach, using pipe-viewer (pv):

  • sudo apt install pv
  • pv -pra file1 > file2

Second approach, using rsync:

  • rsync --progress file1 file2

Editors

Open two files in Vim side by side (i.e. in two vertical panes)

  • vim -O file1 file2

To switch between the panes, type CTRL-w CTRL-w.

Open two files in Vim stacked (i.e. in two horizontal panes)

  • vim -o file1 file2

Open the difference between two files side by side

  • vimdiff file1 file2

Archives

Pipe output of curl into tar to extract

  • curl http://example.org/fubar.tar.gz | tar -xzv

Tar source directory and exclude .git

 function Tar {
  tar -c -f $1.tar -v --exclude-vcs $1
  bzip2 -9 $1.tar
 }

Processes

Detect that a particular user is running a particular process

  • pgrep -u fred -n doom

Print the current system load

  • uptime
  • cat /proc/loadavg | cut -d ' ' -f 1-3
  • top | head -1

Schedule programs to run via cron

  • crontab -e

Users

  • To su to another user without carrying over your environment variables, which is what is does by default, use su - username.

Memory

Get free RAM

  • free -h

Print swap space

  • swapon --show

Print detailed kernel info about memory

  • cat /proc/meminfo

Permissions

Let a user run a command with sudo but without entering their password

Edit /etc/sudoers thus:

 username hostname = NOPASSWD: /usr/sbin/rfkill

Give a user audio playback permission

 sudo usermod -aG audio username

 audio:x:29:pi,pulse,myusername
 pulse-access:x:125:pi,pulse,myusername

Power management

Terms

  • TDP = Thermal Design Power, which is defined as the power needed to cool the CPU.
  • PL1 = Power Level 1, which is CPU sustained power.
  • PL2 = Power Level 2, which is CPU temporary peak power.
  • Tau = Maximum duration at PL2.

Identify what processes are using the most power

  • powertop

Identify what suspend operations are available

  • cat /sys/power/state

Suspend the system manually (without locking the GUI)

  • (as root) echo mem > /sys/power/state
  • (as root) systemctl suspend

Hibernate the system manually

This saves RAM to the swap area, which needs to be at least the same size as your RAM.

  • (as root) echo disk > /sys/power/state
  • (as root) systemctl hibernate

Hybrid sleep

This is just suspend and hibernate combined. It allows fast recovery due to the suspend but if power is lost, it can still recover due to hibernation having saved RAM to disk.

  • (as root) systemctl hybrid-sleep

Limit a particular process's use of the CPU

This is especially useful if the computer that's running Linux is fanless e.g. a Macbook Air, and you want to prevent overheating, or if the computer is old and you want to ensure it lasts as long as possible.

 cpulimit -p PID -l percentage

Get your laptop battery's charge etc.

  function battery {
    VOLTS_NOW=`cat /sys/class/power_supply/BAT0/voltage_now`
    DRAW_NOW=`cat /sys/class/power_supply/BAT0/current_now`
    WATTS_NOW=`echo "$VOLTS_NOW * $DRAW_NOW / 1000000000000.0 " | bc -l | head -1`
    DRAW_AVERAGE=`cat /sys/class/power_supply/BAT0/current_avg`
    CHARGE=`cat /sys/class/power_supply/BAT0/charge_now`
    FULL=`cat /sys/class/power_supply/BAT0/charge_full`
    PERCENT=$((100*$CHARGE/$FULL))
    printf "Present voltage: %d\n" $VOLTS_NOW
    printf "Present current draw: %d\n" $DRAW_NOW
    printf "Present power draw: %g W\n" $WATTS_NOW
    printf "Average draw: %d\n" $DRAW_AVERAGE
    printf "Present charge: %d\n" $CHARGE
    printf "Full charge: %d\n" $FULL
    printf "Percent charge: %d%%\n" $PERCENT
    CYCLES=`cat /sys/class/power_supply/BAT0/cycle_count`
    printf "Battery cycle count: %d\n" $CYCLES
  }

You might also compare the full charge as designed versus the full charge that you can achieve nowadays.

 cat /sys/class/power_supply/BAT0/charge_full
 cat /sys/class/power_supply/BAT0/charge_full_design

Get current CPU temperature

There can be many different temperature sensors inside a computer and each computer and Linux distro may handle temperature a little differently.

  • sensors | grep temp

This works fine on the Raspberry Pis.

 function t {
     string=$(cat /sys/class/thermal/thermal_zone0/temp)
     tinteger=$(($string/1000))
     tenths=$(($string/100))
     tfraction=$(($tenths % $tinteger))
     echo "CPU temperature is $tinteger.$tfraction °C"
 }

On some distros you can access the CPU coretemp in /sys:

 function t3 {
     pushd /sys/bus/platform/devices > /dev/null
      cd coretemp.0/hwmon/hwmon?
      for a in temp?_label; do
       I=`echo $a | sed "s/label/input/"`
       L=`cat $a`
       T1000=`cat $I`
       T=$(($T1000/1000))
       echo $L: $T"°C"
      done
     popd > /dev/null
 }

Get/set current CPU power governor

 sudo apt install cpufrequtils
 sudo cpufreq-info
 sudo cpufreq-set -c 0 -g ondemand

If you want to set the frequency ranges for each core, you must follow it with MHz.

Print Intel sleep mode

 cat /sys/power/mem_sleep

Disable Intel TurboBoost

This can reduce CPU heat and power usage.

 echo 1 > /sys/devices/system/cpu/intel_pstate/no_turbo

Get TDP on Intel systems

 sudo apt install powercap-utils
 sudo powercap-info -p intel-rapl

Bluetooth

Block or unblock Bluetooth

  • rfkill block bluetooth
  • rfkill unblock bluetooth

Scan for BLE devices

  1. Run bluetoothctl
  2. Type power on
  3. Type scan on

This will produce a list of nearby devices.

Once you have the MAC address of your device, you can use additional commands like pair or info.

Send a (small) file via Bluetooth

I tested these commands between a Raspberry pi 4 and an Android phone. They seem to work for small files, but for larger ones the transfers failed or hanged.

  • blueman-sendto
  • bluetooth-sendto

Webcam, cameras

Identify the webcam type using Video 4 Linux

 sudo apt install v4l-utils
 v4l2-ctl -D

Test the webcam

Because Linux often has the video4linux kernel module built into the kernel, it can be simple to test a connected webcam.

 ffplay /dev/video0

Reduce the webcam's frames per second (fps)

This is helpful if Chromium or Firefox are choking on too much video data e.g. when the default fps is 30.

 v4l2-ctl -p 1

This asks for 1 fps, which is usually below the minimum. For instance, the minimum of the Logitech Webcam C925e is 5 fps.

Compilers

Swift

Some useful aliases:

 alias sb="reset; rm -rf .build;swift build -v"
 alias sr="reset; swift run"
 alias spc="swift package clean"
 alias spi="swift package init"
 alias spu="swift package update"

GIT stuff

Some useful functions to civilize git just slightly.

 function ,o {
  git clone --recursive $1
 }
 function ,u {
  git pull
 }
 function ,a {
  git add $*
 }
 function ,c {
  git commit
 }
 function ,l {
  git log $1
 }
 function ,- {
  git checkout -- $*
 }
 function ,p {
  git push
 }
 function ,r {
  git rm $*
 }
 function ,s {
  git status
 }

Popups

There are a few ways to generate pop-ups from the command line.

  • xmessage "This is a test" -geo 300x300
  • zenity --title "Title" --entry --text "Enter some text:"
  • zenity --info --title "Title" --text "Message"

To generate a system notification:

  • notify-send "notification title" "notification text"

GRUB

Change the background image that GRUB shows:

 IMG=/usr/share/images/desktop-base/desktop-grub.png
 sudo cp newBackground.png $IMG
 sudo update-grub

Firefox

Firefox is perhaps the best browser available right now, especially since Chrome blocked the use of the UBlock Origin adblocker.

Firefox keeps your browsing data in ~/.mozilla/firefox but there are only 3 files that are of vital importance in there:

  1. The bookmarks file (places.sqlite).
  2. The saved passwords files (key4.db and logins.json).

From time to time Firefox can become clogged with tracking information and scripts that run in the background (Web Workers). Firefox's ability to remove these is limited i.e. its menu options for clearing history and browsing data don't remove all of it.

The ultimate way to clear out Firefox but keep your bookmarks and saved passwords is to perform the following operation which gets rid of everything except the above three files:

  1. Quit Firefox.
  2. Chdir into ~/.mozilla/firefox and find your current profile directory e.g. XXXXXXX.default-esr.
  3. Chdir into that and list the files.
  4. Backup the bookmarks file (places.sqlite) e.g. copy it to your home directory.
  5. Backup the passwords files (key4.db and logins.json) e.g. copy it to your home directory.
  6. Chdir ../.. and rename firefox to something innocuous e.g. firefox.bak.
  7. Run Firefox to create a new ~/.mozilla/firefox directory.
  8. Quit Firefox.
  9. Copy your bookmarks and password files back into your new profile directory, which will have a different name.
  10. Run Firefox and it should have your backed-up bookmarks and passwords.

Malware

Malware scanners that are used on Linux include:

ClamAV sudo apt install clamav
Rootkit Hunter sudo apt install rkhunter
Chkrootkit sudo apt install chkrootkit
Lynis sudo apt install lynis
Linux Malware Detect Search for: maldetect

Systemd

Clean up unnecessary journal bloat

 sudo journalctl --rotate
 sudo journalctl --vacuum-time=1s

Switch from graphical to console login

Change the default.target symbolic link in /etc/systemd/system to point to multi-user.target instead of graphical.target.

List all running services

 sudo systemctl list-units --type=service --state=running

Shut down the Apache web server

 sudo service apache2 stop

Or more generally:

 sudo service httpd stop

Screen

The GNU Screen utility is useful for creating side-by-side terminal sessions within one terminal e.g. for when you are comparing two files.

It is invoked by just typing screen.

Commands:

  • Ctrl-a | = split the terminal into two terminals horizontally i.e. side by side.
  • Ctrl-a S = split the terminal into two terminals vertically i.e. above and below.
  • Ctrl-a Tab = switch to the next terminal.
  • Ctrl-a c = start a BASH shell in an empty terminal.
  • Ctrl-a Q = quit a terminal.

iOS Device Access

You can mount an iOS device's filesystem using iFuse. You can also fetch information about the device using iDevice utilities e.g. ideviceinfo.

 sudo apt install ifuse
 sudo apt install libimobiledevice-utils
 sudo apt install ideviceinstaller

Add these to your bashrc:

 function phone {
  # Get access to most files but not apps' files.
  mkdir -p ~/iPhone
  ifuse ~/iPhone
 }
 function unphone {
  fusermount -u ~/iPhone
 }
 function iphone_info {
  ideviceinfo | grep -e DeviceName -e HardwareModel -e DeviceClass -e CPUArchitecture
  ideviceinfo | grep -e ProductName -e ProductType -e ProductVersion
 }
 function list_ios_apps {
  ideviceinstaller -l
 }

ifuse allows you to read and write files within the iOS filesystem.

That said, iOS won't recognize any files that you write into the iOS filesystem. This is due to the fact that iOS keeps track of all files that it knows about in SQLite databases and doesn't recognized anything that's not in such a database.

Solution 1: VLC for video and audio files

While iOS doesn't recognize files that you write into its filesystem, the VLC app does, but only if you put your files in its Documents folder. You can then play your videos and MP3s from the VLC app. In order to get access to its Documents directory, you have to mount that folder separately from the main root filesystem.

  • As a rule, you cannot access any app's files without mounting that app's Documents directory separately from mounting the general iOS filesystem.
  • It is a rare iOS app that lets you mount its Documents directory from Linux but VLC is one of them.

 function VLC {
  mkdir -p ~/VLC
  ifuse --documents org.videolan.vlc-ios ~/VLC
 }
 VLC; cp ~/Downloads/sn0988.mp3 ~/VLC

Transfer from VLC to Files

Once you copy files into VLC's Documents directory, you can use Files to copy them into Files's directory.

For example, copy a PDF into VLC, use Files to copy it into Downloads, then read it from there.

Solution 2: Overwrite existing files

You can overwrite images (and video files) in the DCIM/100APPLE directory that will then be viewable under iOS. Since VLC exists, this is really only useful for image files.

 # Image file
 convert ~/myImage.jpg ~/iPhone/DCIM/100APPLE/IMG_1234.PNG

After you overwrite an image (or video) file, you must delete its thumbnail in order to force iOS to regenerate it based on your new file. Here is a command to delete all thumbnails:

 rm -f ~/iPhone/PhotoData/Thumbnails/V2/DCIM/100APPLE/IMG_????.???/5005.JPG

Using an iOS device as a storage device

Because the iOS filesystem is writeable, you can use your iOS device as storage drive. For instance, if you have large files like ISO files or LLM models, it might be more convenient to put them on your phone rather than carry around thumb drives, which you could misplace.

qemu

To run Qemu without a GUI, this is ostensibly possible using the switches -nographic and/or -display curses on Linux.

Fun fact, these don't work on a Mac.

Cross compilation

If you have an x86 system you can cross-compile for aarch64 by installing these tools:

 sudo apt install gcc-aarch64-linux-gnu libc6-dev-arm64-cross

Gaming

For Steam, Debian lets you install steam-installer. Before you can use it, you need to enable 32-bit support. But beware, once you enable 32-bit, you may find it is difficult to disable it. If you are short on free hard drive space, you should reconsider.

  • sudo dpkg --add-architecture i386
  • sudo apt install steam-installer

If you don't enable 32-bit functionality, the Steam installer will download hundreds of megabytes of gunk into your .local directory and then tell you it can't run.

Quarantining

It's always a good idea to quarantine code that you don't fully trust, for instance a web browser.

There are a few ways to do this:

  • Inside a container e.g. Docker
  • Inside a virtual machine e.g. Virtualbox
  • Inside a simulator e.g. Qemu
  • Inside a separate account
  • Using correctly configured firejail

The first three options require installing and running additional software and you have to be willing to trust the makers of and security of those programs.

The fourth option however doesn't require additional software and is quite easy.

The firejail option is interesting but does require that you set up a configuration file in /etc/firejail for the executable containing rules e.g. deny /home.

Quarantining software in a separate account

First, make sure the account exists e.g. sudo adduser brave

Second, you'll want to ensure that any programs that you run in that account will not be able to access your main account's home directory e.g. chmod 700 ~ (and of course any other accounts you might have).

Next you'll prepare to launch the program.

You can just invoke the program by itself:

  • sudo -u brave HOME=/home/brave bash -c /usr/bin/brave-browser

Or you can have it run with limitations:

  • sudo -u brave HOME=/home/brave bash -c "firejail /usr/bin/brave-browser"
  • sudo -u brave HOME=/home/brave bash -c "cpulimit --limit=50 -- /usr/bin/brave-browser"

And of course BASH functions help:

 function br {
  sudo -u brave HOME=/home/brave bash -c "firejail /usr/bin/brave-browser"`
 }

Docker/Podman

If you're concerned that Docker is not fully open source, just install Podman instead which is, and replace docker in each command with podman.

Build an image

 mkdir work_dir
 cd work_dir
 vi Dockerfile
 docker build .

Start and stop docker

If you're using a Linux distro that is afflicted with systemd, there are two easy commands to start and stop the dockerd daemon:

 sudo systemctl start docker
 sudo systemctl stop docker

View current images and containers:

 alias dil="docker image ls"
 alias dcl="docker container ls"
 alias dl="dil; dcl"

Cleanup

 alias dclean="docker system prune -a"

Set up images for various processor types

To run any of the following, just use: docker run -it imagename

x64

 docker build -t x64-image -f ~/DF ~/docker

i386

 docker build --platform=linux/386 -t i386-image -f ~/DF ~/docker

arm64

 docker build --platform=linux/arm64 -t arm64-image -f ~/DF ~/docker

riscv64

 docker build --platform=linux/riscv64 -t riscv64-image -f ~/DF ~/docker

ppc64

 docker build --platform=linux/ppc64le -t ppc64le-image -f ~/DF ~/docker

x64 with VNC

 docker build -t x64-image-vnc -f ~/DF-vnc ~/docker
 docker run -p 5901:5901 x64-image-vnc

The Dockerfile DF-vnc must include some lines to let VNC work e.g.

 ENV DISPLAY=:1
 ENV VNC_PORT=5901
 EXPOSE 5901
 RUN useradd -ms /bin/bash user
 RUN mkdir -p /home/user/.vnc && \
     echo "vncpass" | vncpasswd -f > ~/.vnc/passwd && \
     chmod 600 /home/user/.vnc/passwd
 CMD export USER=user && \
   export XFT_DPI=227 && \
   export DISPLAY=:1 && \
   tightvncserver :1 -geometry 2000x1400 -depth 24 && tail -f /dev/null

Related links

2035851343