Linux Bash Commands Cheat Sheet

Cheat Sheet

Free-electrons provide this rather useful cheet sheet.

Bash Variables

Special Variables
$#Number of command line arguments
$_At shell startup contains absolute filename of shell or script. Afterwards, expands to last argument to the previous command, after expansion
$?Exit value of last command
$$Process number of the shell
$!Process number of last background command
$0First argument - the command name
$nCommand line arguments
$*, $@All arguments on the command line from $1 onwards. "$*" expands to one string "$1 $2 $3...", "$@" expands to "$1" "$2" "$3"...
Arrays
Set: myarray=( 1 2 3 )
myarray[0]=1
Add: Append: myarray+=( 4 5 )
To index: arr=( "${arr[@]:0:2}" "new_element" "${arr[@]:2}" )
Delete: Last element: unset arr[-1], or before Bash 4.3 unset 'arr[${#arr[@]}-1]'
From index (e.g. 2): arr=( "${arr[@]:0:2}" "${arr[@]:3}" ) or unset -v 'arr[2]'
Access: ${myarray[0]} # Print 1st element.
${myarray[@]} # All elements - if in double quotes expand to separate words.
${myarray[*]} # All elements - if in double quotes expand to single word.
${!myarray[@]} # Get indicies.
${arr[@]:s:n} # Get n elements starting at index s.
Length: ${#myarray[*]}
Parameter Substitution
Default parameters: ${parameter:-default} # Get variable value. If not defined return default.
${parameter:=default} # Get variable value. If not defined SET variable to default and return value.
${parameter:?err_msg [cmd]} # If set use, else exit script with err_msg. If cmd set then exec cmd.
Variable Length: ${#var}
Remove Substring: ${var#pattern} # Remove SHORTEST part of $pattern that matches FRONT end of $var.
${var##pattern} # Remove LONGEST part of $pattern that matches FRONT end of $var.
${var%pattern} # Remove SHORTEST part of $pattern that matches BACK end of $var.
${var%%pattern} # Remove LONGEST part of $pattern that matches BACK end of $var.
Substring Replacement: ${var:pos} # Expand from offset pos.
${var:pos:len} # Expand from offset pos max len chars.
${var/pat/repl} # Replace first match of pat with repl. If repl blank, delete.
${var/#pat/repl} # Replace if matched front end of pat with repl. If repl blank, delete.
${var/%pat/repl} # Replace if matched back end of pat with repl. If repl blank, delete.
${var//pat/repl} # As above but global over all matches of pat.
Change case: ${var,} # Set first character to lowercase
${var,,} # Set first character to lowercase
${var^} # Set first character to uppercase
${var^^} # Set entire string to uppercase

Bash History Expansion

!4 Display and execute the fourth commnd in the history table
!-2 Display and execute command 2 commands back
!! or !-1 Display and execute previous command
!word Search backwards through command history for first command that starts with "word". If found, display and execute command
!?word Search backwards through command history for first command that contains with "word". If found, display and execute command
^str1^str2^ Change the first occurence of str1 in previous command to str2
!!:s/str1/str2 Same as previous
!!:gs/str1/str2 Change ALL occurences of str1 in previous command to str2
!!:n Get the nth argument of the previous command
!!:$< or !$ Get last argument or the previous command

Archiving:

Create archive tar c(jz)vf archive.tar.gz dir
z: make gzip
j: bzip2

zip -r archive.zip <files>
Extract archive tar xvf archive.tar.[gz|bz2|lzma|xz]
unzip archive.zip
List archive contents tar tvf archive.tar.[gz|bz2|lzma|xz]

File Systems:

Mount

Mount a device:
sudo mkdir my-mount-directory; sudo mount /dev/sdb1 my-mount-directory

Mount a Windows share:
sudo mount -t cifs -o username=USERNAME,uid=$(id -u),gid=$(id -g),forceuid,forcegid //192.168.7.20/ut.ids.base /mnt/laptop
You can also add password and domain objects if required. The force(uid|gid) option override any ownership info that may be sent by the server and the (uid|gid) specifiers give your user permission to r/w the mount.

Unmount sudo umount /dev/sdb1
Format sudo mkfs.(ntfs|ext4|vfat) /dev/sdb1
Space used/avail in FS df -h /dev/sda or df -h /home/jehtech
Space used by specific files/dirs du
Get size of dir/file du -sh[c] dir.
The -c option produces a grand total.
Check what process has a file open: lsof /path/to/file

Packages:

List packages: dpkg -l
Package ver: dpkg -s <packagename>
Install package: apt-get install <packagename>[=<versionno>]

Users, Groups, Permissions

Change permissions: chmod [ugo]+[rwx] file or chmod -R [ugo]+[rwx] dir
Change the group assigned to a resource: sudo chgroup <group-name> <resource>
Change the owner/group/all permissions
assigned to a resource:
sudo chmod [ogu]+[rwx] <resource>
Create a new user: adduser USER-NAME PASSWORD
Add a user to a group: sudo adduser <new-username> <group-name>
Create a new group: sudo groupadd <new-groupname>
List groups user belongs too: groups
List all groups on system: cut -d: -f1 /etc/group
Get my groups: id -G -n <username>
Give user sudo: usermod -a -G sudo <username>
Change password: sudo passwd <username> or just for yourself passwrd
Example - create new user account:
# Create a new user...
sudo adduser the_new_guy new_guys_password

# Setup SSH Access...
# Must have a private/public keypair on your local machine and copy the public
# key onto the server's authorized-keys file for the user.
sudo mkdir /home/the_new_guy/.ssh/
sudo chmod 0700 /home/the_new_guy/.ssh/
sudo -- sh -c "echo 'ssh-ed25519 AAAA ... rest of pub key ...' > /home/the_new_guy/.ssh/authorized_keys"
sudo chown -R the_new_guy:the_new_guy /home/vivek/.ssh/

# Setup sudoer ability [optional]
sudo usermod -a -G sudo the_new_guy

Services

System V Init

Start/Stop/Restart: service <servicename> start|stop|restart

Systemd

List services: systemctl list-units
systemctl list-unit-files [--all]
Control service: sudo systemctl [start|restart|stop|enable|disable] <servicename>
Service status: sudo systemctl status <servicename>
Service specific status: sudo systemctl is-active|is-enabled|is-failed <servicename>
Show unit file: systemctl cat <servicename>
Edit unit file: sudo systemctl edit [--full] <servicename> && sudo systemctl daemon-reload
Find system service files: ls /lib/systemd/system/

View journal entries: sudo journalctl [-kb] [-u <unit name>], -b for current boot messages, -k for kernel messages.
Logs since boot: journalctl -b N.
N = 0: this boot, N = -1: last boot etc.
Edit /etc/systemd/journald.conf and under [Journal] set storage=persistent to keep logs across boots.
Logs since date: journalctl --since "YYYY-MM-DD HH:MM:SS"
journalctl --since yesterday
journalctl --since HH:MM --until "X hours ago"
Filter by service: journalctl -u <service-name:>.service
Kernel messages: journalctl -k

Uncomplicated Firewall (UFW)

Status: ufw status verbose
Enable Firewall: ufw enable
Deny All Incoming: ufw deny incoming
Allow All Outgoing: uft default allow outgoing
Allow SSH Incoming: ufw allow ssh
Rate Limit (SSH): ufw limit ssh/tcp
Allow Protocol/Port Range: ufw allow 1234:4321/(ip|udp|tcp)
Allow Specific IP Incoming: ufw allow x.x.x.x
Allow SSH from IP range: ufw allow proto tcp from 192.1.1.0/24 port 22
Show Numbered Rules: ufw status numbered
Delete Rules: ufw delete (allow|deny) ...
See Apps: ufw app list
Get App Info:: ufw app info app-name

System Info

System version: uname -a
Kernel version: uname -r
Hostname & IP: hostname [-I]
List PCI:
lspci -tv
       ^
       Show a tree-like diagram containing all buses, bridges, devices and connections                  
                

lspci -k -nn -v
       ^  ^^  ^
       ^  ^^  Verbose
       ^  Show PCI vendor and device codes as both numbers and names    
       Show kernel drivers handling each device
List USB: lsusb -tv
udevadm info --name=/dev/ttyUSBx --attribute-walk
List USB Serial Devices: sudo cat /proc/tty/driver/usbserial
Memory fitted: sudo lshw -c memory
Free memory: free -m
vmstat -s -S M | grep mem
CPU: lscpu

Networking:

Network Manager Client:
Wifi status: nmcli r wifi
Turn wifi on/off: nmcli r wifi off|on
List wifi devices: nmcli d wifi list
Connect to wifi networkL nmcli --ask con up <network-name>, or
nmcli device wifi connect <network-name< password <password>
Show connections: nmcli con show
nmap:
Discover running services: sudo netstat -plunt
Associate ports & services: less /usr/share/nmap/nmap-services
Scan for host OS: sudo nmap -O <addr>
Scan specific port: sudo nmap -p <port num< <addr>
Ping range of ports: nmap -sP 192.168.0.0-255
Routes:
Check routing table: route [-n]
Check routing table: route [-n]
Add route: sudo route add -net 192.168.a.b gw 192.168.a.1 netmask 255.255.255.0 dev ethX
Add default route: sudo route add default gw 192.168.a.1
Delete route: sudo route del -net 192.168.a.b gw 192.168.a.1 netmask 255.255.255.0 dev ethX
Delete default route: sudo route del default gw 192.168.a.1

Fail2Ban:

Get status: sudo fail2ban status
View logs: sudo cat /var/log/fail2ban.log
Start/stop/reload/get status: fail2ban-client start|stop|reload|status [jail-name]
Un-ban an IP sudo fail2ban-client set jail-name unbanip ip-address

Other little bits:

Switch Java vers: alternatives --config java