© 2020-2024 by Zack Smith. All rights reserved.
- Hardware
- Storage
- Networking
- USB
- Display/GUI
- Browsers
- Package managers
- BASH
- Files
- Archives
- Processes
- Permissions
- Power Management
- Bluetooth
- Webcam
- GIT
- Popups
- GRUB
- Systemd
- Screen
- iOS Device Access
- Gaming
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 drives
The easiest way is to type:
- lsblk
Or, if you like typing in passwords, 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 |
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,
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
- Use
fdisk diskImage.img
to find the starting sector of the partition that you want to mount. - 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 { |
How to erase a CD-RW disc
function wipe_cd { |
Create a RAM disk
- sudo mount -t tmpfs -o size=4000M,mode=1777 myRAMdisk /mnt
Why use a RAM disk?
- It's the fastest possible drive.
- Using a RAM disk avoids wear and tear on physical drives (whether solid state drives or spinning hard disks).
- It operates separately from physical drives, therefore doesn't slow down access to them.
- 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 { |
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: |
Print a log file continuously as it updates
sudo tail -f /var/log/daemon.log |
Set the volume label of an EXT4 drive
e2label /dev/sdX MyLabel |
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 { |
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 \ |
List all network connections of a program
- lsof -c program -i TCP -i UDP -a
Example: |
List all programs listening on TDP and UDP ports
netstat -ltup |
Print your machine's IP address
hostname -I |
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
- Edit /etc/resolvconf.conf
- You will change the line name_servers=
- Add a reliable server e.g.
- 1.1.1.1 (cloudflare)
- 9.9.9.9
- 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 { |
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
- Use ping to get the IP address for a domain's web server.
- Use whois to get CIDR IP range(s) for that server.
- 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 |
How to get the SHA-1 HTTPS fingerprint of a site
function fp { |
USB Tips
Print USB devices
- lsusb [-v]
Enable a printer that was mysteriously stopped
- Get the precise printer name with
lpq
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 { |
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 display information
- xwininfo -root | grep -e Width -e Height -e Depth
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, where2
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:
- large screens
- medium screens (1080p)
- 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 { |
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
Debian
Print all install packages
dpkg -l |
BASH Tips
Redirect stderr to a file
command 2> file |
Redirect stderr to stdout
command 2>&1 |
Convert a string to lower case
string="THIS IS A 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" |
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 |
Note that prefix* must not be in quotes.
Detect whether a string begins with some suffix
if [[ "myfile.mp4" == *mp4 ]]; then |
Note that suffix must not be in quotes.
Remove the extension from a filename
filename=xyz.jpg |
Extract just the extension of a filename or file path
path="/home/me/Photo.tiff" |
This prints tiff
.
Extract just the filename of path
path="/home/me/Photo.tiff" |
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 |
Generate a random number from 0...n
n=255 |
Generate a random password
date | sed s/^/$RANDOM/ | shasum |
Find all occurrences of a string only within text files
# grep recursively all text files |
Find all occurrences of a string only within C/C++ header files, case insensitive
# grep recursively all, case insentitive header files |
Extract the nth line of a text file
tail -n +LINENO file | head -1 |
Array usage
# Defintion |
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.
- display image file
- edit image file
Or
- play audio file.
- edit audio file.
I created BASH functions for each type of operation, such as this one for opening a file:
# Open |
Working with 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
Print metadata about a media file
- ffprobe video.mp4
Print a binary file in hexadecimal form
- od -x file
Print a binary file in hex and ascii forms
- od -a -x file
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
Archives
Tar source directory and exclude .git
function 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
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 |
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.
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 { |
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 |
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 { |
On some distros you can access the CPU coretemp in /sys:
function t3 { |
Identify what processes are using the most power
- powertop
Get/set current CPU power governor
sudo apt install cpufrequtils |
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 |
Bluetooth
Block or unblock Bluetooth
- rfkill block bluetooth
- rfkill unblock bluetooth
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 |
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.
GIT stuff
Some useful functions to civilize git just slightly.
function ,o { |
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 |
Systemd
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
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 |
Add these to your bashrc:
function phone { |
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 { |
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 |
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.
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.
Related links
- MacOS command-line tips
- FFMPEG video file manipulation tips
- ImageMagick image file manipulation tips
- Make Slackware Linux ISO
- Numerous Linux tips