Electrical-Forenics Home ray@RayFranco.com                       601.529.7473
   © Dr. Ray Franco, PhD, PE  -  208 Fairways Dr., Vicksburg, MS 39183

Updated: May 26, 2024

Linux

In 2021, there were 27.9 millions of lines of source code in the Linux Kernel, and 1.3 million in systemd. Systemd is the first process to run when Linux starts. It is a replacement for init. The "D" in Systemd is for Directories. Systemd is used by most but all Linux distributions. Android does not use systemd.

Wild Cards

* # Matches any number of characters
? # Matches any single character
[ ]    # Matches any character in the brackets (character set)

 

Examples:
F* # Matches any string that begins with "F"
*.txt # Matches any string that ends with ".txt"
*ing # Matches any string that ends with "ing"
F*ing   # Matches any string that begins with "F" and ends in "ing".
S?n # Matches any 3 character string that begins with "S" and end with "n"
S[ao]n   # Matches "San" and "Son"

List

ls [option]... [file or dir]...
 -l   # long
 -a   # all including hidden
 -A   # almost all does not list . or ..
 -h   # human readable file size
 -d   # directory details
 -F   # Forward slash appended to directories
 -t   # time sort (newest first)
 -S   # Size sort (smallest first)
 -X   # eXtension sort (file type) - no macOS
 -r   # reverse sort order
 -R   # Recursive list subdirectories and file
 -s   # Allocated size (sparse file size)

 

Examples
ls  // list visible files in the current directory
ls -alhF Documents  // list all files in the Document directory
ls -lh file_1.txt  // list file_1.txt if it exist else print error message
ls -alh file_1.txt Documents  // list both

File and directory names can contain wild cards * and ?, but the ls command does NOT support regular expressions.

References:

  1. How to use the ls command on linux - Dave McKay
  2. Warning Advanced - Display Only Hidden Files in Linux

tree

Very Useful, but not installed by Default on most Linux Distributions

  options
  -a all including hidden
  -d directory list only
  -L Level of Directories
  -t time sort
  -f full file name
  -r reverse sort
  -p permissions
  -u user name
  -g group name
  -D Date
  -s size
  -h human readable size
  -P Pattern Match
  -x exlude other file systems
  -dirsfirst directories first
Examples  
ls  // list visible files in the current directory
ls -alhF documents  // list all files in the document directory
ls -lh file_1.txt  // list file_1.txt if it exist else print error message
ls -alh file_1.txt documents  // list both

Linux File-system Hierarchy Standard (FHS)

/bin /sbin /usr/bin/ and usr/sbin : Where executable programs are stored.

/bin : OS critical binary (executable) files

/sbin : - Support S binary (executable) files

/usr : User files (non-administator files - sometimes install by a user).

/usr/bin : User binary (executable) files.

/usr/sbin : Support user binary (executable) files.

/opt : Optional or added files by the user.

/boot : files need to boot the OS.

/var : Where varable-length files, like log files are stored.

/etc : Where configuration (.conf) files are stored.

/dev : Where device files are stored.

/mnt : mount

/media : CD ROM and Thumb Drives

/temp : temporary

/proc : runing process (porgrams)

/home : Where User Directories are stored.

Move, Copy, Remove

To avoid mistakes, it is best practice to place a forward slash, "/", after directories.

Move

mv [options] source... destination
mv source_file destination_directory
mv source_file destination_dir/new_file_name
# moves and renames the file
mv file_1 file_2 ... destination_dir
mv source_file distination_file
# rename the file
mv source_directory destination_directory
# if the destination dir exist, places the source dir inside the destination dir else renames the directory. To avoid mistakes, use destination_directory/.
 
Options
-i (Interactive) - ask before overwritting
-n (No Overwite)
-u (Update) - Overwrite only if newer

 

copy

cp [options] source... destination
cp source_file destination_directory
cp source_file destination_dir/new_file_name
# copies and renames the file
cp file_1 file_2 ... destination_dir
cp -r source_directory destination_directory
# copies the soure directory and files into destination directory
cp source_file distination_file
# makes a copy with a different name
 
Options
-r (recursive)
-i (Interactive) - ask before overwritting
-n (No Overwite)
-u (Update) - Overwrite only if newer

Remove

rm [option]... [file]...
  -i   # Interactive - ask before removing
  -r or -R   # Recursive - removes files and directories
  -f   # force - will prompt for removal of write protected files.

rm -rf / wil remove all file and distroy the ssytem. There is no undo command in linux. When using wild cards, it is a good idea to test first using the ls command.

Make & Remove Directories
mkdir directory...  # make directory
rmdir directory...   # Will only remove Empty directories
  # use rm -r to remove non-empty directories

 

View Files Contents

catSend contents of a file to the console. It also concatenates files.
head -n 20Send the 1st 20 lines ile to the console (default is 10 lines).
tailsSend the last 10 lines to the console (can also use -n #_of_lines).
more Pagination: enter: next line ; space_bar: next page; q : quite.
less Pagination: enter: next line ; space_bar or n : next page; N : previous page; q : quite; also can search / .

Find

find [path...] [options] [expression]

 -maxdepth 3 # search 3 dir deep
 -type f # search for file
 -type d # search for directory
 -name pattern# search for file name
 -iname pattern# case insensitive name
 -atime +6 # accessed > 6 days
 -mtime -6 # modified < 6 days
 -ctime 6 # changed 6 days ago
 -amin +60 # accessed > 60 min
 -mmin -60 # modified < 6 min
 -cmin 60 # changed 60 min ago
 -size +600MB # files > 600MB
 -o # logical OR
 -a # logical AND - default if not specified
 -not # logical NOT
 -regex expression # regular expression
 -regextype type # default type is emacs

The find command support regular expressions via the -regex option.
The -name option does NOT support regular expressions.
Regular Expressions Cheat Sheet

If the find command does not have permission to open a directory you will get a permisson denied error message. To not show the error messages use redirection i.e. 2> /dev/null (redirect errors to /dev/null).

Examples:
 
# In the Vidoes directory, all mp4 files:
find ~/Videos/ -maxdepth 1 -iname '*.mp4'
 
# Starting in the users home directory, find all files greater than 1.1 GB:
find ~/ >1.1GB
 
# Starting in the current directory, find files modified less than 2 hours ago:
find . - mmin -120
find . - mmin -$[60*2] # using command expansion  
# Starting in the documents directory, find all text and script (shell) files:
find ~/Documents/ -name '*.txt' -o -name "*.sh"
 
# In the documents directory, find all non-text files:
find ~/Documents/ -maxdepth 1 -not -name '*.txt'
 
# Sarting in the current dir, find text files not in hidden directories:
find ! -path "./.*" -name "*.txt"

Examples:
find ~/Videos/ -iname '*.mp4' # find, in the Video directory, all mp4 files.
find . -iname '*.txt' -name "*.sh" # find, in the current directory, all text and script (shell) files.
find ~/ >1.1GB # find, in the home directory, files greater than 1.1 GB.
find . - mmin -120 # find, in the current directory, files modified less than 120 minutes ago.

References:

Locate filename

Not Installed by Default in Debian or MacOS

Locate does not search for files, but looks in a database. To update the database:
 
sudo updatedb
 
Indexed the entire hard drive. May take considerable time to update the db.

(MacOS)
WARNING: The locate database (/var/db/locate.database) does not exist. To create the database, run the following command:
 
sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist
 
Please be aware that the database can take some time to generate; once the database has been created, this message will no longer appear.

Locate Commands

whereis command   List all the locations of a command
which command   List the first locations of a command
type command   List the locations & type of a command

Global Regular Expression Print (grep)
Searches a file or files for a pattern and prints the line with the pattern.
The -E option replaces the deprecated egrep version of grep.
The -F option replaces the deprecated fgrep version of grep.

grep [options] pattern filename[s]
-i case insensitive
-w whole word
-v inverse line that don't match
-n line number
-r recursive
-l list files with matching lines
-E extended regexp
-F fixed (plain) strings

Examples:
grep -i "Pi" /etc/passwd  # prints user pi line
grep -E "pi|dave" /ect/passwd  # prints users pi and dave lines
grep -v "^#" etc/sudoers.d  # filter out comment lines

File Permissions and Ownership

Permissions:

chmod (change mode)

Syntax: chmod mode [,mode]... file_name...
 
u (user/owner), g (group), o (other/everyone else), a (all, which is the default)
r (read), w (write), x (execute)

Examples:

chmod u+x file_name   // add execute privillage to user/ower
chmod g-w file_name   // remove write privillage from group
chmod o+r file_name   // add read privillage to other
chmod o+xr file_name   // add execute and read privillage to other
chmod o=xr file_name   // other can execute and read but can not write
chmod u+x,g-w file_name   // add execute to user - remove write from group
chmod u+x,g-w file_name   // add execute to user - remove write from group
chmod a+x   // give all the execute privillage
chmod +x   // give all the execute privillage
chmod 755   // same as u=rwx, g=r-x, o=r-x

chomod -R 755 folder_name: rwx, r-x, r-x to folder and files recursively

Advanced

The setuid flag [2] can also be set with the chmod command:

sudo chmod u+s executable_file_name

This is oten used to allow users on a computer system to run programs with temporarily elevated privileges to perform a specific task such as mounting a network drive.

References:

  1. How to Use the chmod Command on Linux.
  2. Wikipedia - setuid

Ownership:

chown - Change Owner

There is also:

However, chown can do either or both.

Unix Name

uname [options]
 -a --all  # all
 -s --kernel-name  # kernel name (default)
 -o --operating-system  # operating system
 -r --kernel-release  # kernel revision
 -m --machine-name  # machine hardware name
 -p --processor  # processor name
 -i --hardware-platform  # hardware platform
 -n --nodename   # network node hostname
--versioin   # version number
--help   # help

History

History Commands

fc - fix command

Alias

Alias Commands

Variables

Set Command

Change Shell

chsh [options]
 -s  full_path_shell_name  # change shells
 -h --help  # change shells

example:
chsh -s $(which dash) // change shell to dash

grep user_name /etc/passwd

Interactive Mode

wc [opinions] file_name
  new lines, words, bytes
-w  words
-l lines
-c bytes
-m char
id [opinions] [user_name]
 -u user effective ID
 -g group effective ID
 -G All Groups
 -n names instead of ID:ws
 -r real instead of effective
 --version version number
 --help help

Miscellaneous Commands

pwd - present working director

date - date and time

whoami

id

top

hostnamectl

hostname

Administrative Commands

Change Password

passwd

The passwd command will prompt you for the new password twice. You do not have to enter the old password.

userdel [-r]

-r removes user's files - best practice

usermod [options]

List Hardware

The Raspberry Pi OS does not install package by default. To install it:

sudo apt install lshw

lshw [options]

List Block Devices

lsblk [options] [device...]
 -a   # all
 -D --discard   # discard (TRIM UNMAP)
 -f --fs   # filesystem info
 -m   # permissions
 -S --scsi   # scsi only
 -v   # version

References:

  1. Linux Handbook - lsblk Command Examples

List USB Devices

lsuab [options]
 -t   # tree view
 -d   # by device
 -s   # specific device by bus
 -v   # verbose output

Secure Shell - ssh

ssh username@IP_address(or host_name) [options]
 -p port_number

The ssh sever configuration file is: /etc/ssh/sshd_config. At the end of sshd_config, you can add an allow and/or a deny list:

AllowUsers user1 user 2
DenyUsers user3 user 4

The allow/deny directives are processed in the following order: DenyUsers, AllowUsers, DenyGroups, and finally AllowGroups.

References:

  1. How do I use SSH to connect to a remote server in Linux | ssh Command
  2. 19 Common SSH Commands in Linux with Examples
  3. ssh command in Linux with examples
  4. How To Use SSH to Connect to a Remote Server
  5. 4 Ways to Transfer Files Between Remote and Local Systems Over SSH
  6. FTPS vs. SFTP vs. SCP

Secure File Transfer Protocol - sftp

sftp [options] username@IP_address(or host_name)
 -P port_numberCaptial P - Port to Connect to on Remote
 -oPort=number - Specify Port to Connect to on Remote

exit

get [-afpR] remote-path [local-path]
  -R # Recursive
  -p # preserve ownership and file properities
put [-afpR] local-path [remote-path]
  -R # Recursive
  -p # preserve ownership and file properities

"SFTP allows you to run a command using the local shell by adding an exclamation mark (!) before the command. This lets users run commands that aren't a part of the standard SFTP shell on the local system [].

Advantages

Disadvantages:

References:

  1. How To Use SFTP to Securely Transfer Files with a Remote Server
  2. SSH File Transfer Protocol (SFTP): Get SFTP client & server
  3. SFTP File Transfer Protocol
  4. Guide to Linux sftp Command with Examples
  5. FTPS vs. SFTP vs. SCP
  6. How to Use SFTP Commands and Options

Debian Package Manager

apt - Advanced Package Tool

sudo apt update # update the package list
sudo apt upgrade# install updates
sudo apt upgrade -y# Ans. yes, install the updates
  
apt install pkg_name # install package
apt purge pkg_name # remove package and config files
apt remove pkg_name # remove package leave config files
  
apt list --upgradable # see which packages will be upgraded
apt list --installed # list installed packages
apt list --installed pkg_name# see if package is installed
dpkg -s package_name# see which version of package is installed

It is possible to keep some packages from updating:
 
sudo apt-mark hold pkg_name    # Keep a Package from Updating
sudo apt-mark unhold pkg_name  # Release Hold and Allow Package Update
sudo apt-mark showhold     # Show held packages
 

To see previous versions of packages that were install:
 
apt-cache policy pkg_name
 
This is usefully when you want to roll back to a previous version.

sudo apt install pkg_name=version_number

You can also directly install packages that you compile or download load from the Internet:

sudo dpkg -i pkg_name.deb

Fordora Package Manager - dnf

dnf [options] <command> [<args>...]

optionscommandargs // full ststem update
update  // full ststem update
check-update  // check for packages that can be updated
upgrade  // update all packages
upgradepackage_name // update package_name
searchpackage_name // update package_name
installpackage_name // update package_name
removepackage_name // update package_name
autoremovepackage_name // update package_name
downgradepackage_name // install previous version of package_name
update--exclude package_name // update package_name

To exclude a package from being updated, you have to add an excludepkgs statement to the /etc/dnf/dnf.conf file [1]. For example:

excludepkgs=nordvpn

There may be another way to exclude installing or updating packages by first installing dnf plugins. There are both core and third party plugins for dnf. I want my OS to be as lean as possible.

References:

  1. Using the DNF software package manager
  2. 25+ dnf command examples in Linux [Cheat Sheet]
  3. The dnf package manager in Linux – A complete reference

Drives, Partitions, and Volumes

Definations:

TypeNameDrive Name
scsi, sata, usb scsi devicesd followed by a letter
eMMC & SD card embedded Multi-Media Card block mmcblock for by p and a number
NVMe Non-Volatile Memory express nvme followed by a number, the letter n, drive number

Reference:

  1. Youtube - ExplainingComputers - Linux Survival Guide #1: Distros & Drives
  2. eMMC vs. SSD: Not All Solid-State Storage Is Equal

Mount & Umount

mount /dev/Partition_to_Mount Path_Where_to_Mount

umount Path_to_Umount

Note, the command is "umount" and NOT "unmount"

Most Linux Distros with a GUI (Desktop) will automatically mount a USB drive at /media. However, Debian still requires you to unmount the usb drive with the command line before detaching it from the USB port. In 2023, the Raspberry Pi OS added an eject button to unmount the drive. The easiest way to unmount a drive is use the lsblk command (below) and copy the mount point then run "sudo umount" and paste in the mount point.

lsblk (list Block Devices)

Syntax: lsblk [-options]
   

Appearently, lsblk will not list network drives. However, the following command will:

df -h

References:

  1. How To Mount and Unmount Drives on Linux

Does NOT work for backing up a Raspberry Pi Image!

DD (Data Duplicator)

Syntax DD if=input_file of=output_file
    bs=? (block size) default 512
    conv=sparse
    status=progress

Examble - Using DD to create an image file of a disk:

sudo dd if=/dev/sda of=/home/pi/2023_10_13_Dell_Rpi_Zero2W.img conv=sparse status=progress

Unfortunately, for a 128 GB micro SD card with only around 7 GB being used, this took over two hours to complete. This is because dd copies empty blank spaces. Without the conv=sparse option the image file size and the allocated space is 128 GBytes. With the conv=spare option, the apparent file size is 128 GBytes, but the allocated space is only 7.1 GB. To see the allocated space use the -s option with ls or use the du command.

The reverse process was much faster:

sudo dd=2023_10_13_Dell_Rpi_Zero_2W.ing of=sda

It took less than 10 minutes. However, the SD was NOT bootable by a Raspberry Pi 4.

Disk Free

Syntax: df [-options]
    -h       : human readable
    --total : calculate totals

df works only on mounted devices.

lsblk (list Block)

Syntax: lsblk [-options]
   

Format Disk

Syntax: sudo fdisk [-options]
   -l list
   -h help

Unfornately, if you do not put sudo in front of this command, the system returns "command not found", which is misleading.

Disk Usage

Syntax: du [options] [directory/file]

References:

  1. Baeldung - When and How to Use the dd Command
  2. How to Create an Image of a Raspberry Pi SD Card? (Win/Linux/Mac)
  3. Linux Handbook - DD Command
  4. What are sparse files in Linux?
  5. Tom's Hardware -How to Back Up Your Raspberry Pi as a Disk Image
  6. How to Create an Image of a Raspberry Pi SD Card? (Win/Linux/Mac)
  7. Pi Magazine - Back up your Raspberry Pi: how to save and restore files
  8. DigiKey 3/22/2023 - How To Back Up a Raspberry Pi SD Card
  9. How to Clone Raspberry Pi SD Card on Windows, Linux and macOS

Raspberry Pi - SD Card Copier

To make a backup image of everything on the system disk, the Rasberry Pi Organization gave us the accessory program "SD Card Copier" [1]. They stated "this has been difficult with the command-line tools that we recommended in the past" [1]. It works well; but it is strickly a GUI program, which excludes it from being used with servers without a GUI.

I have not been able to copy a SD-Card connected via USB to another SD-Card connected via USB. In fact, if their chipset are the same, I can not even get two SD-Cards connnected via USB to mount. This program should have been called SD-Image Copier instead of SD-Card Copier.

References:

  1. May 13, 2016 - The latest update to Raspbian - SD Card Copier

Libre Office Fonts

You can add the Microsoft true type core fonts to Libre Office with the following command:

sudo apt install ttf-mscorefonts-installer

However, you will have to accept Microsoft's EULA.

References