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
Append: myarray+=( 4 5 )
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} # 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 sudo mkdir my-mount-directory; sudo mount /dev/sdb1 my-mount-directory
Unmount sudo umount /dev/sdb1
Format sudo mkfs.(ntfs|ext4|vfat) /dev/sdb1
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
List USB: lsusb -tv
Free memory: free -m
vmstat -s -S M | grep mem

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

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