This commit is contained in:
2025-06-29 20:18:01 +03:00
commit 97ec40544b
4 changed files with 1642 additions and 0 deletions

912
Bash Cheat Sheet.md Normal file
View File

@@ -0,0 +1,912 @@
---
title: Bash Cheat Sheet
created: '2025-06-29T16:47:55.778Z'
modified: '2025-06-29T16:57:39.219Z'
---
# Bash Cheat Sheet
### A cheat sheet for bash commands.
>**Note** 💡<br>
> - A single hyphen `-` is used to represent a short option, such as `-a`.<br>
> - A double hyphen `--` is used to denote a long option, such as `--all`.<br>
> - Example command : `ls -a|--all` (List all directories). Can use either use the short or long options.
> - Both short and long options were incorporated for educational purposes, allowing users to choose the preferred format.<br>
> - It's important to note that not all commands have both short and long options. Some commands may only have short options, while others may only have long options.
### Contents
- [Command Information](#command-information)
- [Command History](#command-history)
- [Navigating Directories](#navigating-directories)
- [Creating Directories](#creating-directories)
- [Moving Directories](#moving-directories)
- [Deleting Directories](#deleting-directories)
- [Creating Files](#creating-files)
- [Standard Output, Error and Input](#standard-output-standard-error-and-standard-input)
- [Moving Files](#moving-files)
- [Deleting Files](#deleting-files)
- [Reading Files](#reading-files)
- [Sorting Files](#sorting-files)
- [File Permissions](#file-permissions)
- [Finding Files](#finding-files)
- [Find in Files](#find-in-files)
- [Replace in Files](#replace-in-files)
- [File Editor](#file-editor)
- [Symbolic Links](#symbolic-links)
- [Compressing Files](#compressing-files)
- [Decompressing Files](#decompressing-files)
- [Packages](#packages)
- [Disk Usage](#disk-usage)
- [Memory Usage](#memory-usage)
- [Shutdown and Reboot](#shutdown-and-reboot)
- [Identifying Processes](#identifying-processes)
- [Process Priority](#process-priority)
- [Killing Processes](#killing-processes)
- [Date & Time](#date--time)
- [Scheduled Tasks](#scheduled-tasks)
- [User Mangement](#user-management)
- [HTTP Requests](#http-requests)
- [Network Troubleshooting](#network-troubleshooting)
- [DNS](#dns)
- [Hardware](#hardware)
- [System Information](#system-information)
- [Terminal Multiplexers](#terminal-multiplexers)
- [Secure Shell Protocol (SSH)](#secure-shell-protocol-ssh)
- [Secure Copy](#secure-copy)
- [Bash Profile](#bash-profile)
- [Bash Script](#bash-script)
#
## Command Information
```bash
man chmod # Display page manual of a command
man -f|--whatis chmod # Display short description about a command
man -k|--apropos permission # Display all related commands from a specific keyword
chmod --help # Display usage options of a command
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Command History
```bash
history # View all previous commands
history | grep foo # View the commands using a specific word
history | grep -E|--extended-regexp -i|--ignore-case 'foo1|foo2|foo3' # View the commands using more than 1 specific word(case sensitive)
history | head -n|--lines 3 # View the first 3 executed commands
history 3 # View the last 3 executed commands
history -d 99 # Clear a command from a specific line
history -c # Clears all history commands
!! # Run the last command executed
touch foo.sh # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<┐
chmod +x !$ # !$ is the last argument of the last command i.e. foo.sh <<<<┘
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Navigating Directories
```bash
pwd # Print current directory path
ls # List directories
ls -a|--all # List directories including hidden
ls -l # List directories in long form
ls -l -h|--human-readable # List directories in long form with human readable sizes
ls -t # List directories by modification time, newest first
stat foo.txt # List size, created and modified timestamps for a file
stat foo # List size, created and modified timestamps for a directory
tree # List directory and file tree
tree -a # List directory and file tree including hidden
tree -d # List directory tree
cd foo # Go to foo sub-directory
cd # Go to home directory
cd ~ # Go to home directory
cd - # Go to the previously chosen directory
pushd foo # Go to foo sub-directory and add previous directory to stack
popd # Go back to directory in stack saved by `pushd`
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Creating Directories
```bash
mkdir foo # Create a directory
mkdir foo bar # Create multiple directories
mkdir -p|--parents foo/bar # Create nested directory
mkdir -p|--parents {foo,bar}/baz # Create multiple nested directories
mktemp -d|--directory # Create a temporary directory
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Moving Directories
```bash
cp -R|--recursive foo bar # Copy directory
mv foo bar # Move directory
rsync -z|--compress -v|--verbose /foo /bar # Copy directory, overwrites destination
rsync --ignore-existing -a|--archive -z|--compress -v|--verbose /foo /bar # Copy directory, without overwriting destination
rsync -avz /foo username@hostname:/bar # Copy local directory to remote directory
rsync -avz username@hostname:/foo /bar # Copy remote directory to local directory
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Deleting Directories
```bash
rmdir foo # Delete non-empty directory
rm -r|--recursive foo # Delete directory including contents
rm -r|--recursive -f|--force foo # Delete directory including contents, ignore nonexistent files and never prompt
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Creating Files
```bash
touch foo.txt # Create file or update existing files modified timestamp
touch foo.txt bar.txt # Create multiple files
touch {foo,bar}.txt # Create multiple files
touch test{1..3} # Create test1, test2 and test3 files
touch test{a..c} # Create testa, testb and testc files
mktemp # Create a temporary file
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Standard Output, Standard Error and Standard Input
```bash
echo "foo" > bar.txt # Overwrite file with content
echo "foo" >> bar.txt # Append to file with content
ls exists 1> stdout.txt # Redirect the standard output to a file
ls noexist 2> stderror.txt # Redirect the standard error output to a file
ls > out.txt 2>&1 # Redirect standard output and error to a file
ls > /dev/null # Discard standard output and error
read foo # Read from standard input and write to the variable foo
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Moving Files
```bash
cp foo.txt bar.txt # Copy file
mv foo.txt bar.txt # Move file
rsync -z|--compress -v|--verbose /foo.txt /bar # Copy file quickly if not changed
rsync -z|--compress -v|--verbose /foo.txt /bar.txt # Copy and rename file quickly if not changed
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Deleting Files
```bash
rm foo.txt # Delete file
rm -f|--force foo.txt # Delete file, ignore nonexistent files and never prompt
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Reading Files
```bash
cat foo.txt # Print all contents
less foo.txt # Print some contents at a time (g - go to top of file, SHIFT+g, go to bottom of file, /foo to search for 'foo')
head foo.txt # Print top 10 lines of file
tail foo.txt # Print bottom 10 lines of file
tail -f|--follow foo.txt # Print bottom 10 lines of file updating with new data
open foo.txt # Open file in the default editor
wc foo.txt # List number of lines words and characters in the file
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Sorting Files
```bash
sort foo.txt # Sort file (ascending order)
sort -r|--reverse foo.txt # Sort file (descending order)
sort -n|--numeric-sort foo.txt # Sort numbers instead of strings
sort -t|--field-separator: -k 3n /foo/foo.txt # Sort by the third column of a file
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## File Permissions
| # | Permission | rwx | Binary |
| - | - | - | - |
| 7 | read, write and execute | rwx | 111 |
| 6 | read and write | rw- | 110 |
| 5 | read and execute | r-x | 101 |
| 4 | read only | r-- | 100 |
| 3 | write and execute | -wx | 011 |
| 2 | write only | -w- | 010 |
| 1 | execute only | --x | 001 |
| 0 | none | --- | 000 |
For a directory, execute means you can enter a directory.
| User | Group | Others | Description |
| - | - | - | - |
| 6 | 4 | 4 | User can read and write, everyone else can read (Default file permissions) |
| 7 | 5 | 5 | User can read, write and execute, everyone else can read and execute (Default directory permissions) |
- u - User
- g - Group
- o - Others
- a - All of the above
```bash
ls -l /foo.sh # List file permissions
chmod +100 foo.sh # Add 1 to the user permission
chmod -100 foo.sh # Subtract 1 from the user permission
chmod u+x foo.sh # Give the user execute permission
chmod g+x foo.sh # Give the group execute permission
chmod u-x,g-x foo.sh # Take away the user and group execute permission
chmod u+x,g+x,o+x foo.sh # Give everybody execute permission
chmod a+x foo.sh # Give everybody execute permission
chmod +x foo.sh # Give everybody execute permission
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Finding Files
Find binary files for a command.
```bash
type -a wget # Display all locations of executable
which -a wget # Display all locations of executables
whereis wget # Find the binary, source, and manual page files
```
`locate` uses an index and is fast.
```bash
updatedb # Update the index
locate foo.txt # Find a file
locate --ignore-case # Find a file and ignore case
locate f*.txt # Find a text file starting with 'f'
```
`find` doesn't use an index and is slow.
```bash
find /path -name foo.txt # Find a file
find /path -iname foo.txt # Find a file with case insensitive search
find /path -name "*.txt" # Find all text files
find /path -name foo.txt -delete # Find a file and delete it
find /path -name "*.png" -exec pngquant {} # Find all .png files and execute pngquant on it
find /path -type f -name foo.txt # Find a file
find /path -type d -name foo # Find a directory
find /path -type l -name foo.txt # Find a symbolic link
find /path -type f -mtime +30 # Find files that haven't been modified in 30 days
find /path -type f -mtime +30 -delete # Delete files that haven't been modified in 30 days
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Find in Files
```bash
grep 'foo' /bar.txt # Search for 'foo' in file 'bar.txt'
grep 'foo' /bar -r|--recursive # Search for 'foo' in directory 'bar'
grep 'foo' /bar -R|--dereference-recursive # Search for 'foo' in directory 'bar' and follow symbolic links
grep 'foo' /bar -l|--files-with-matches # Show only files that match
grep 'foo' /bar -L|--files-without-match # Show only files that don't match
grep 'Foo' /bar -i|--ignore-case # Case insensitive search
grep 'foo' /bar -x|--line-regexp # Match the entire line
grep 'foo' /bar -C|--context 1 # Add N line of context above and below each search result
grep 'foo' /bar -v|--invert-match # Show only lines that don't match
grep 'foo' /bar -c|--count # Count the number lines that match
grep 'foo' /bar -n|--line-number # Add line numbers
grep 'foo' /bar --colour # Add colour to output
grep 'foo\|bar' /baz -R # Search for 'foo' or 'bar' in directory 'baz'
grep --extended-regexp|-E 'foo|bar' /baz -R # Use regular expressions
grep -E 'foo|bar' /baz -R # Use regular expressions
```
### Replace in Files
```bash
sed 's/fox/bear/g' foo.txt # Replace fox with bear in foo.txt and output to console
sed 's/fox/bear/gi' foo.txt # Replace fox (case insensitive) with bear in foo.txt and output to console
sed 's/red fox/blue bear/g' foo.txt # Replace red with blue and fox with bear in foo.txt and output to console
sed 's/fox/bear/g' foo.txt > bar.txt # Replace fox with bear in foo.txt and save in bar.txt
sed -i|--in-place 's/fox/bear/g' foo.txt # Replace fox with bear and overwrite foo.txt
sed -i|--in-place '/red fox/i\blue bear' foo.txt # Insert blue bear before red fox and overwrite foo.txt
sed -i|--in-place '/red fox/a\blue bear' foo.txt # Insert blue bear after red fox and overwrite foo.txt
sed -i|--in-place '10s/find/replace/' foo.txt # Replace the 10th line of the file
sed -i|--in-place '10,20s/find/replace/' foo.txt # Replace in the file 10-20 lines
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
### File Editor
```bash
nano # Open a new file in nano
nano foo.txt # Open a specific file
nano -m|--mouse foo.txt # Enable the use of the mouse
nano -l|--linenumbers foo.txt # Show line numbers in front of the text
nano +line,10 foo.txt # Open file positioning the cursor at the specified line and column
nano -B|--backup foo.txt # Create a backup file (`foo~`) when saving edits
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Symbolic Links
```bash
ln -s|--symbolic foo bar # Create a link 'bar' to the 'foo' folder
ln -s|--symbolic -f|--force foo bar # Overwrite an existing symbolic link 'bar'
ls -l # Show where symbolic links are pointing
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Compressing Files
### zip
Compresses one or more files into *.zip files.
```bash
zip foo.zip /bar.txt # Compress bar.txt into foo.zip
zip foo.zip /bar.txt /baz.txt # Compress bar.txt and baz.txt into foo.zip
zip foo.zip /{bar,baz}.txt # Compress bar.txt and baz.txt into foo.zip
zip -r|--recurse-paths foo.zip /bar # Compress directory bar into foo.zip
```
### gzip
Compresses a single file into *.gz files.
```bash
gzip /bar.txt foo.gz # Compress bar.txt into foo.gz and then delete bar.txt
gzip -k|--keep /bar.txt foo.gz # Compress bar.txt into foo.gz
```
### tar -c
Compresses (optionally) and combines one or more files into a single *.tar, *.tar.gz, *.tpz or *.tgz file.
```bash
tar -c|--create -z|--gzip -f|--file=foo.tgz /bar.txt /baz.txt # Compress bar.txt and baz.txt into foo.tgz
tar -c|--create -z|--gzip -f|--file=foo.tgz /{bar,baz}.txt # Compress bar.txt and baz.txt into foo.tgz
tar -c|--create -z|--gzip -f|--file=foo.tgz /bar # Compress directory bar into foo.tgz
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Decompressing Files
### unzip
```bash
unzip foo.zip # Unzip foo.zip into current directory
```
### gunzip
```bash
gunzip foo.gz # Unzip foo.gz into current directory and delete foo.gz
gunzip -k|--keep foo.gz # Unzip foo.gz into current directory
```
### tar -x
```bash
tar -x|--extract -z|--gzip -f|--file=foo.tar.gz # Un-compress foo.tar.gz into current directory
tar -x|--extract -f|--file=foo.tar # Un-combine foo.tar into current directory
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Packages
```bash
apt update # Refreshes repository index
apt search wget # Search for a package
apt show wget # List information about the wget package
apt list --all-versions wget # List all versions of the package
apt install wget # Install the latest version of the wget package
apt install wget=1.2.3 # Install a specific version of the wget package
apt remove wget # Removes the wget package
apt upgrade # Upgrades all upgradable packages
apt clean # Clears out the local repository of downloaded package files
dpkg -i|--install package_name.deb # Install deb file
dpkg -P package_name.deb # Remove a deb file installion (including configuration files)
rpm -i|--install package_name.rpm # Install a rpm file installion
rpm -e package_name.rpm # Remove rpm file installion (including dependencies)
```
### Install package source code
```bash
tar zxvf sourcecode.tar.gz
cd sourcecode
./configure
make
make install
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Disk Usage
```bash
df # List disks, size, used and available space
df -h|--human-readable # List disks, size, used and available space in a human readable format
du # List current directory, subdirectories and file sizes
du /foo/bar # List specified directory, subdirectories and file sizes
du -h|--human-readable # List current directory, subdirectories and file sizes in a human readable format
du -d|--max-depth # List current directory, subdirectories and file sizes within the max depth
du -d 0 # List current directory size
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Memory Usage
```bash
free # Show memory usage
free -h|--human # Show human readable memory usage
free -h|--human --si # Show human readable memory usage in power of 1000 instead of 1024
free -s|--seconds 5 # Show memory usage and update continuously every five seconds
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Shutdown and Reboot
```bash
shutdown # Shutdown in 1 minute
shutdown now # Immediately shut down
shutdown +5 # Shutdown in 5 minutes
shutdown -r|--reboot # Reboot in 1 minute
shutdown -r|--reboot now # Immediately reboot
shutdown -r|--reboot +5 # Reboot in 5 minutes
shutdown -c # Cancel a shutdown or reboot
reboot # Reboot now
reboot -f # Force a reboot
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Identifying Processes
```bash
top # List all processes interactively
htop # List all processes interactively
ps ax # List all processes
pidof foo # Return the PID of all foo processes
CTRL+Z # Suspend a process running in the foreground
bg # Resume a suspended process and run in the background
fg # Bring the last background process to the foreground
fg 1 # Bring the background process with the PID to the foreground
sleep 30 & # Sleep for 30 seconds and move the process into the background
jobs # List all background jobs
jobs -p # List all background jobs with their PID
lsof # List all open files and the process using them
lsof -itcp:4000 # Return the process listening on port 4000
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Process Priority
Process priorities go from -20 (highest) to 19 (lowest).
```bash
nice -n -20 foo # Change process priority by name
renice 20 PID # Change process priority by PID
ps -o ni PID # Return the process priority of PID
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Killing Processes
```bash
CTRL+C # Kill a process running in the foreground
kill PID # Shut down process by PID gracefully. Sends TERM signal.
kill -9 PID # Force shut down of process by PID. Sends SIGKILL signal.
pkill foo # Shut down process by name gracefully. Sends TERM signal.
pkill -9 foo # force shut down process by name. Sends SIGKILL signal.
killall foo # Kill all process with the specified name gracefully.
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Date & Time
```bash
date # Print the date and time
date --iso-8601 # Print the ISO8601 date
date --iso-8601=ns # Print the ISO8601 date and time
date -s "02 DEC 2020 12:02:02" # Manually change date and time
dpkg-reconfigure tzdata # Change date/timezone
uptime # Print how long the system has been running
time tree # Print amount of time to tree takes to execute
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Scheduled Tasks
```pre
* * * * *
Minute, Hour, Day of month, Month, Day of the week
```
```bash
crontab -l # List cron tab
crontab -e # Edit cron tab in a file editor
crontab /path/crontab # Load cron tab from a file
crontab -l > /path/crontab # Save cron tab to a file
* * * * * foo # Run foo every minute
*/15 * * * * foo # Run foo every 15 minutes
0 * * * * foo # Run foo every hour
15 6 * * * foo # Run foo daily at 6:15 AM
44 4 * * 5 foo # Run foo every Friday at 4:44 AM
0 0 1 * * foo # Run foo at midnight on the first of the month
0 0 1 1 * foo # Run foo at midnight on the first of the year
at -l # List scheduled tasks
at -c 1 # Show task with ID 1
at -r 1 # Remove task with ID 1
at now + 2 minutes # Create a task in a file editor to execute in 2 minutes
at 12:34 PM next month # Create a task in a file editor to execute at 12:34 PM next month
at tomorrow # Create a task in a file editor to execute tomorrow
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## User Management
```bash
sudo su # Switch to root user
sudo foo # Execute commands(has permission denied) as the root user
sudo nano /foo/foo.txt # Open directories and files(is not writable) as the root user
su username # Switch to a different user
passwd # To change the password of a user
adduser username # To add a new user
userdel username # To remove user
userdel -r|--remove username # To remove user with home directory and mail spool
usermod -a|--append -G|--groups GROUPNAME USERNAME # To add a user to a group
deluser USER GROUPNAME # To remove a user from a group
last # Display information of all the users logged in
last username # Display information of a particular user
w # Display who is online
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## HTTP Requests
```bash
curl https://example.com # Return response body
curl -i|--include https://example.com # Include status code and HTTP headers
curl -L|--location https://example.com # Follow redirects
curl -O|--remote-name foo.txt https://example.com # Output to a text file
curl -H|--header "User-Agent: Foo" https://example.com # Add a HTTP header
curl -X|--request POST -H "Content-Type: application/json" -d|--data '{"foo":"bar"}' https://example.com # POST JSON
curl -X POST -H --data-urlencode foo="bar" http://example.com # POST URL Form Encoded
wget https://example.com/file.txt # Download a file to the current directory
wget -O|--output-document foo.txt https://example.com/file.txt # Output to a file with the specified name
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Network Troubleshooting
```bash
ifconfig # Display all network card and interface information
ifconfig -a # Display information of all network cards (including those that are not started at boot)
ifconfig eth0 # Display specific device information
ifconfig eth0 up # Turn on the network card
ifconfig eth0 down # Turn off the network card
ifconfig eth0 192.168.120.56 # Configure IP address for network card
curl ifconfig.me # Obtain external IP address
ping example.com # Send multiple ping requests using the ICMP protocol
ping -c 10 -i 5 example.com # Make 10 attempts, 5 seconds apart
ip addr # List IP addresses on the system
ip route show # Show IP addresses to router
netstat -i|--interfaces # List all network interfaces and in/out usage
netstat -l|--listening # List all open ports
traceroute example.com # List all servers the network traffic goes through
mtr -w|--report-wide example.com # Continually list all servers the network traffic goes through
mtr -r|--report -w|--report-wide -c|--report-cycles 100 example.com # Output a report that lists network traffic 100 times
nmap 0.0.0.0 # Scan for the 1000 most common open ports on localhost
nmap 0.0.0.0 -p1-65535 # Scan for open ports on localhost between 1 and 65535
nmap 192.168.4.3 # Scan for the 1000 most common open ports on a remote IP address
nmap -sP 192.168.1.1/24 # Discover all machines on the network by ping'ing them
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## DNS
```bash
dig example.com # Show query information of domain A records
dig -4 example.com # Show IPv4 A records
dig -6 example.com # Show IPv6 AAA records
dig example.com @nameserver # Show query of a specific nameserver
dig example.com -p 123 # Show query of a specific port number
cat /etc/resolv.conf # Nameservers file
cat /etc/systemd/resolved.conf # DNS resolver config file
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Hardware
```bash
lsusb # List USB devices
lspci # List PCI hardware
lshw # List all hardware
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## System Information
```bash
uname -s # Print kernel name
uname -r # Print kernel release
uname -m # Print Architecture
uname -o # Print Operating System
uname -a # Print all Systen info
lsb_release -a # Print distribution-specific information
dpkg --print-architecture # Print-architecture by name
cat /proc/cpuinfo # Show cpu info
cat /proc/meminfo # Show memory info
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Terminal Multiplexers
Start multiple terminal sessions. Active sessions persist reboots. `tmux` is more modern than `screen`.
```bash
tmux # Start a new session (CTRL-b + d to detach)
tmux ls # List all sessions
tmux attach -t 0 # Reattach to a session
screen # Start a new session (CTRL-a + d to detach)
screen -S foo # Start a new named session
screen -ls # List all sessions
screen -R 31166 # Reattach to a session
exit # Exit a session
reset # Reset the terminal(when binary and the terminal state is messed up)
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Secure Shell Protocol (SSH)
```bash
ssh hostname # Connect to hostname using your current user name over the default SSH port 22
ssh -i foo.pem hostname # Connect to hostname using the identity file
ssh user@hostname # Connect to hostname using the user over the default SSH port 22
ssh user@hostname -p 8765 # Connect to hostname using the user over a custom port
ssh ssh://user@hostname:8765 # Connect to hostname using the user over a custom port
```
Set default user and port in `~/.ssh/config`, so you can just enter the name next time:
```bash
$ cat ~/.ssh/config
Host name
User foo
Hostname 127.0.0.1
Port 8765
$ ssh name
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Secure Copy
```bash
scp foo.txt ubuntu@hostname:/home/ubuntu # Copy foo.txt into the specified remote directory
scp ubuntu@hostname:/home/ubuntu/foo.txt /C:\Users\Admin # Copy foo.txt from the specified remote directory
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Bash Profile
- bash - `.bashrc`
- zsh - `.zshrc`
```bash
# Always run ls after cd
function cd {
builtin cd "$@" && ls
}
# Prompt user before overwriting any files
alias cp='cp --interactive'
alias mv='mv --interactive'
alias rm='rm --interactive'
# Always show disk usage in a human readable format
alias df='df -h'
alias du='du -h'
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)
## Bash Script
### Variables
```bash
#!/bin/bash
foo=123 # Initialize variable foo with 123
declare -i foo=123 # Initialize an integer foo with 123
declare -r foo=123 # Initialize readonly variable foo with 123
echo $foo # Print variable foo
echo ${foo}_'bar' # Print variable foo followed by _bar
echo ${foo:-'default'} # Print variable foo if it exists otherwise print default
export foo # Make foo available to child processes
unset foo # Make foo unavailable to child processes and current session
```
### Environment Variables
```bash
#!/bin/bash
set # List all environment variables
echo $PATH # Print PATH environment variable
export FOO=Bar # Set an environment variable
```
### Functions
```bash
#!/bin/bash
greet() {
local world="World"
echo "$1 $world"
return "$1 $world"
}
greet "Hello"
greeting=$(greet "Hello")
```
### Exit Codes
```bash
#!/bin/bash
exit 0 # Exit the script successfully
exit 1 # Exit the script unsuccessfully
echo $? # Print the last exit code
```
### Conditional Statements
#### Boolean Operators
- `$foo` - Is true
- `!$foo` - Is false
#### Numeric Operators
- `-eq` - Equals
- `-ne` - Not equals
- `-gt` - Greater than
- `-ge` - Greater than or equal to
- `-lt` - Less than
- `-le` - Less than or equal to
- `-e` foo.txt - Check file exists
- `-z` foo - Check if variable exists
#### String Operators
- `=` - Equals
- `==` - Equals
- `-z` - Is null
- `-n` - Is not null
- `<` - Is less than in ASCII alphabetical order
- `>` - Is greater than in ASCII alphabetical order
#### If Statements
```bash
#!/bin/bash
[[
if [[$foo = 'bar']]; then
echo 'one'
elif [[$foo = 'bar']] || [[$foo = 'baz']]; then
echo 'two'
elif [[$foo = 'ban']] && [[$USER = 'bat']]; then
echo 'three'
else
echo 'four'
fi
]]
```
#### Inline If Statements
```bash
#!/bin/bash
[[ $USER = 'rehan' ]] && echo 'yes' || echo 'no'
```
#### While Loops
```bash
#!/bin/bash
[
declare -i counter
counter=10
while [$counter -gt 2]; do
echo The counter is $counter
counter=counter-1
done
]
```
#### For Loops
```bash
#!/bin/bash
for i in {0..10..2}
do
echo "Index: $i"
done
for filename in file1 file2 file3
do
echo "Content: " >> $filename
done
for filename in *;
do
echo "Content: " >> $filename
done
```
#### Case Statements
```bash
#!/bin/bash
echo "What's the weather like tomorrow?"
read weather
case $weather in
sunny | warm ) echo "Nice weather: " $weather
;;
cloudy | cool ) echo "Not bad weather: " $weather
;;
rainy | cold ) echo "Terrible weather: " $weather
;;
* ) echo "Don't understand"
;;
esac
```
[⬆ ʀᴇᴛᴜʀɴ ᴛᴏ ᴄᴏɴᴛᴇɴᴛꜱ](#contents)

603
Command Line.md Normal file
View File

@@ -0,0 +1,603 @@
---
title: Command Line
created: '2025-06-29T17:03:50.849Z'
modified: '2025-06-29T17:13:03.188Z'
---
# Command Line
- [Meta](#meta)
- [Basics](#basics)
- [Everyday use](#everyday-use)
- [Processing files and data](#processing-files-and-data)
- [System debugging](#system-debugging)
- [One-liners](#one-liners)
- [Obscure but useful](#obscure-but-useful)
- [macOS only](#macos-only)
- [Windows only](#windows-only)
- [More resources](#more-resources)
## Meta
Scope:
- This guide is for both beginners and experienced users. The goals are *breadth* (everything important), *specificity* (give concrete examples of the most common case), and *brevity* (avoid things that aren't essential or digressions you can easily look up elsewhere). Every tip is essential in some situation or significantly saves time over alternatives.
- This is written for Linux, with the exception of the "[macOS only](#macos-only)" and "[Windows only](#windows-only)" sections. Many of the other items apply or can be installed on other Unices or macOS (or even Cygwin).
- The focus is on interactive Bash, though many tips apply to other shells and to general Bash scripting.
- It includes both "standard" Unix commands as well as ones that require special package installs -- so long as they are important enough to merit inclusion.
Notes:
- To keep this to one page, content is implicitly included by reference. You're smart enough to look up more detail elsewhere once you know the idea or command to Google. Use `apt`, `yum`, `dnf`, `pacman`, `pip` or `brew` (as appropriate) to install new programs.
- Use [Explainshell](http://explainshell.com/) to get a helpful breakdown of what commands, options, pipes etc. do.
## Basics
- Learn basic Bash. Actually, type `man bash` and at least skim the whole thing; it's pretty easy to follow and not that long. Alternate shells can be nice, but Bash is powerful and always available (learning *only* zsh, fish, etc., while tempting on your own laptop, restricts you in many situations, such as using existing servers).
- Learn at least one text-based editor well. The `nano` editor is one of the simplest for basic editing (opening, editing, saving, searching). However, for the power user in a text terminal, there is no substitute for Vim (`vi`), the hard-to-learn but venerable, fast, and full-featured editor. Many people also use the classic Emacs, particularly for larger editing tasks. (Of course, any modern software developer working on an extensive project is unlikely to use only a pure text-based editor and should also be familiar with modern graphical IDEs and tools.)
- Finding documentation:
- Know how to read official documentation with `man` (for the inquisitive, `man man` lists the section numbers, e.g. 1 is "regular" commands, 5 is files/conventions, and 8 are for administration). Find man pages with `apropos`.
- Know that some commands are not executables, but Bash builtins, and that you can get help on them with `help` and `help -d`. You can find out whether a command is an executable, shell builtin or an alias by using `type command`.
- `curl cheat.sh/command` will give a brief "cheat sheet" with common examples of how to use a shell command.
- Learn about redirection of output and input using `>` and `<` and pipes using `|`. Know `>` overwrites the output file and `>>` appends. Learn about stdout and stderr.
- Learn about file glob expansion with `*` (and perhaps `?` and `[`...`]`) and quoting and the difference between double `"` and single `'` quotes. (See more on variable expansion below.)
- Be familiar with Bash job management: `&`, **ctrl-z**, **ctrl-c**, `jobs`, `fg`, `bg`, `kill`, etc.
- Know `ssh`, and the basics of passwordless authentication, via `ssh-agent`, `ssh-add`, etc.
- Basic file management: `ls` and `ls -l` (in particular, learn what every column in `ls -l` means), `less`, `head`, `tail` and `tail -f` (or even better, `less +F`), `ln` and `ln -s` (learn the differences and advantages of hard versus soft links), `chown`, `chmod`, `du` (for a quick summary of disk usage: `du -hs *`). For filesystem management, `df`, `mount`, `fdisk`, `mkfs`, `lsblk`. Learn what an inode is (`ls -i` or `df -i`).
- Basic network management: `ip` or `ifconfig`, `dig`, `traceroute`, `route`.
- Learn and use a version control management system, such as `git`.
- Know regular expressions well, and the various flags to `grep`/`egrep`. The `-i`, `-o`, `-v`, `-A`, `-B`, and `-C` options are worth knowing.
- Learn to use `apt-get`, `yum`, `dnf` or `pacman` (depending on distro) to find and install packages. And make sure you have `pip` to install Python-based command-line tools (a few below are easiest to install via `pip`).
## Everyday use
- In Bash, use **Tab** to complete arguments or list all available commands and **ctrl-r** to search through command history (after pressing, type to search, press **ctrl-r** repeatedly to cycle through more matches, press **Enter** to execute the found command, or hit the right arrow to put the result in the current line to allow editing).
- In Bash, use **ctrl-w** to delete the last word, and **ctrl-u** to delete the content from current cursor back to the start of the line. Use **alt-b** and **alt-f** to move by word, **ctrl-a** to move cursor to beginning of line, **ctrl-e** to move cursor to end of line, **ctrl-k** to kill to the end of the line, **ctrl-l** to clear the screen. See `man readline` for all the default keybindings in Bash. There are a lot. For example **alt-.** cycles through previous arguments, and **alt-*** expands a glob.
- Alternatively, if you love vi-style key-bindings, use `set -o vi` (and `set -o emacs` to put it back).
- For editing long commands, after setting your editor (for example `export EDITOR=vim`), **ctrl-x** **ctrl-e** will open the current command in an editor for multi-line editing. Or in vi style, **escape-v**.
- To see recent commands, use `history`. Follow with `!n` (where `n` is the command number) to execute again. There are also many abbreviations you can use, the most useful probably being `!$` for last argument and `!!` for last command (see "HISTORY EXPANSION" in the man page). However, these are often easily replaced with **ctrl-r** and **alt-.**.
- Go to your home directory with `cd`. Access files relative to your home directory with the `~` prefix (e.g. `~/.bashrc`). In `sh` scripts refer to the home directory as `$HOME`.
- To go back to the previous working directory: `cd -`.
- If you are halfway through typing a command but change your mind, hit **alt-#** to add a `#` at the beginning and enter it as a comment (or use **ctrl-a**, **#**, **enter**). You can then return to it later via command history.
- Use `xargs` (or `parallel`). It's very powerful. Note you can control how many items execute per line (`-L`) as well as parallelism (`-P`). If you're not sure if it'll do the right thing, use `xargs echo` first. Also, `-I{}` is handy. Examples:
```bash
find . -name '*.py' | xargs grep some_function
cat hosts | xargs -I{} ssh root@{} hostname
```
- `pstree -p` is a helpful display of the process tree.
- Use `pgrep` and `pkill` to find or signal processes by name (`-f` is helpful).
- Know the various signals you can send processes. For example, to suspend a process, use `kill -STOP [pid]`. For the full list, see `man 7 signal`
- Use `nohup` or `disown` if you want a background process to keep running forever.
- Check what processes are listening via `netstat -lntp` or `ss -plat` (for TCP; add `-u` for UDP) or `lsof -iTCP -sTCP:LISTEN -P -n` (which also works on macOS).
- See also `lsof` and `fuser` for open sockets and files.
- See `uptime` or `w` to know how long the system has been running.
- Use `alias` to create shortcuts for commonly used commands. For example, `alias ll='ls -latr'` creates a new alias `ll`.
- Save aliases, shell settings, and functions you commonly use in `~/.bashrc`, and [arrange for login shells to source it](http://superuser.com/a/183980/7106). This will make your setup available in all your shell sessions.
- Put the settings of environment variables as well as commands that should be executed when you login in `~/.bash_profile`. Separate configuration will be needed for shells you launch from graphical environment logins and `cron` jobs.
- Synchronize your configuration files (e.g. `.bashrc` and `.bash_profile`) among various computers with Git.
- Understand that care is needed when variables and filenames include whitespace. Surround your Bash variables with quotes, e.g. `"$FOO"`. Prefer the `-0` or `-print0` options to enable null characters to delimit filenames, e.g. `locate -0 pattern | xargs -0 ls -al` or `find / -print0 -type d | xargs -0 ls -al`. To iterate on filenames containing whitespace in a for loop, set your IFS to be a newline only using `IFS=$'\n'`.
- In Bash scripts, use `set -x` (or the variant `set -v`, which logs raw input, including unexpanded variables and comments) for debugging output. Use strict modes unless you have a good reason not to: Use `set -e` to abort on errors (nonzero exit code). Use `set -u` to detect unset variable usages. Consider `set -o pipefail` too, to abort on errors within pipes (though read up on it more if you do, as this topic is a bit subtle). For more involved scripts, also use `trap` on EXIT or ERR. A useful habit is to start a script like this, which will make it detect and abort on common errors and print a message:
```bash
set -euo pipefail
trap "echo 'error: Script failed: see failed command above'" ERR
```
- In Bash scripts, subshells (written with parentheses) are convenient ways to group commands. A common example is to temporarily move to a different working directory, e.g.
```bash
# do something in current dir
(cd /some/other/dir && other-command)
# continue in original dir
```
- In Bash, note there are lots of kinds of variable expansion. Checking a variable exists: `${name:?error message}`. For example, if a Bash script requires a single argument, just write `input_file=${1:?usage: $0 input_file}`. Using a default value if a variable is empty: `${name:-default}`. If you want to have an additional (optional) parameter added to the previous example, you can use something like `output_file=${2:-logfile}`. If `$2` is omitted and thus empty, `output_file` will be set to `logfile`. Arithmetic expansion: `i=$(( (i + 1) % 5 ))`. Sequences: `{1..10}`. Trimming of strings: `${var%suffix}` and `${var#prefix}`. For example if `var=foo.pdf`, then `echo ${var%.pdf}.txt` prints `foo.txt`.
- Brace expansion using `{`...`}` can reduce having to re-type similar text and automate combinations of items. This is helpful in examples like `mv foo.{txt,pdf} some-dir` (which moves both files), `cp somefile{,.bak}` (which expands to `cp somefile somefile.bak`) or `mkdir -p test-{a,b,c}/subtest-{1,2,3}` (which expands all possible combinations and creates a directory tree). Brace expansion is performed before any other expansion.
- The order of expansions is: brace expansion; tilde expansion, parameter and variable expansion, arithmetic expansion, and command substitution (done in a left-to-right fashion); word splitting; and filename expansion. (For example, a range like `{1..20}` cannot be expressed with variables using `{$a..$b}`. Use `seq` or a `for` loop instead, e.g., `seq $a $b` or `for((i=a; i<=b; i++)); do ... ; done`.)
- The output of a command can be treated like a file via `<(some command)` (known as process substitution). For example, compare local `/etc/hosts` with a remote one:
```sh
diff /etc/hosts <(ssh somehost cat /etc/hosts)
```
- When writing scripts you may want to put all of your code in curly braces. If the closing brace is missing, your script will be prevented from executing due to a syntax error. This makes sense when your script is going to be downloaded from the web, since it prevents partially downloaded scripts from executing:
```bash
{
# Your code here
}
```
- A "here document" allows [redirection of multiple lines of input](https://www.tldp.org/LDP/abs/html/here-docs.html) as if from a file:
```
cat <<EOF
input
on multiple lines
EOF
```
- In Bash, redirect both standard output and standard error via: `some-command >logfile 2>&1` or `some-command &>logfile`. Often, to ensure a command does not leave an open file handle to standard input, tying it to the terminal you are in, it is also good practice to add `</dev/null`.
- Use `man ascii` for a good ASCII table, with hex and decimal values. For general encoding info, `man unicode`, `man utf-8`, and `man latin1` are helpful.
- Use `screen` or [`tmux`](https://tmux.github.io/) to multiplex the screen, especially useful on remote ssh sessions and to detach and re-attach to a session. `byobu` can enhance screen or tmux by providing more information and easier management. A more minimal alternative for session persistence only is [`dtach`](https://github.com/bogner/dtach).
- In ssh, knowing how to port tunnel with `-L` or `-D` (and occasionally `-R`) is useful, e.g. to access web sites from a remote server.
- It can be useful to make a few optimizations to your ssh configuration; for example, this `~/.ssh/config` contains settings to avoid dropped connections in certain network environments, uses compression (which is helpful with scp over low-bandwidth connections), and multiplex channels to the same server with a local control file:
```
TCPKeepAlive=yes
ServerAliveInterval=15
ServerAliveCountMax=6
Compression=yes
ControlMaster auto
ControlPath /tmp/%r@%h:%p
ControlPersist yes
```
- A few other options relevant to ssh are security sensitive and should be enabled with care, e.g. per subnet or host or in trusted networks: `StrictHostKeyChecking=no`, `ForwardAgent=yes`
- Consider [`mosh`](https://mosh.org/) an alternative to ssh that uses UDP, avoiding dropped connections and adding convenience on the road (requires server-side setup).
- To get the permissions on a file in octal form, which is useful for system configuration but not available in `ls` and easy to bungle, use something like
```sh
stat -c '%A %a %n' /etc/timezone
```
- For interactive selection of values from the output of another command, use [`percol`](https://github.com/mooz/percol) or [`fzf`](https://github.com/junegunn/fzf).
- For interaction with files based on the output of another command (like `git`), use `fpp` ([PathPicker](https://github.com/facebook/PathPicker)).
- For a simple web server for all files in the current directory (and subdirs), available to anyone on your network, use:
`python -m SimpleHTTPServer 7777` (for port 7777 and Python 2) and `python -m http.server 7777` (for port 7777 and Python 3).
- For running a command as another user, use `sudo`. Defaults to running as root; use `-u` to specify another user. Use `-i` to login as that user (you will be asked for _your_ password).
- For switching the shell to another user, use `su username` or `su - username`. The latter with "-" gets an environment as if another user just logged in. Omitting the username defaults to root. You will be asked for the password _of the user you are switching to_.
- Know about the [128K limit](https://wiki.debian.org/CommonErrorMessages/ArgumentListTooLong) on command lines. This "Argument list too long" error is common when wildcard matching large numbers of files. (When this happens alternatives like `find` and `xargs` may help.)
- For a basic calculator (and of course access to Python in general), use the `python` interpreter. For example,
```
>>> 2+3
5
```
## Processing files and data
- To locate a file by name in the current directory, `find . -iname '*something*'` (or similar). To find a file anywhere by name, use `locate something` (but bear in mind `updatedb` may not have indexed recently created files).
- For general searching through source or data files, there are several options more advanced or faster than `grep -r`, including (in rough order from older to newer) [`ack`](https://github.com/beyondgrep/ack2), [`ag`](https://github.com/ggreer/the_silver_searcher) ("the silver searcher"), and [`rg`](https://github.com/BurntSushi/ripgrep) (ripgrep).
- To convert HTML to text: `lynx -dump -stdin`
- For Markdown, HTML, and all kinds of document conversion, try [`pandoc`](http://pandoc.org/). For example, to convert a Markdown document to Word format: `pandoc README.md --from markdown --to docx -o temp.docx`
- If you must handle XML, `xmlstarlet` is old but good.
- For JSON, use [`jq`](http://stedolan.github.io/jq/). For interactive use, also see [`jid`](https://github.com/simeji/jid) and [`jiq`](https://github.com/fiatjaf/jiq).
- For YAML, use [`shyaml`](https://github.com/0k/shyaml).
- For Excel or CSV files, [csvkit](https://github.com/onyxfish/csvkit) provides `in2csv`, `csvcut`, `csvjoin`, `csvgrep`, etc.
- For Amazon S3, [`s3cmd`](https://github.com/s3tools/s3cmd) is convenient and [`s4cmd`](https://github.com/bloomreach/s4cmd) is faster. Amazon's [`aws`](https://github.com/aws/aws-cli) and the improved [`saws`](https://github.com/donnemartin/saws) are essential for other AWS-related tasks.
- Know about `sort` and `uniq`, including uniq's `-u` and `-d` options -- see one-liners below. See also `comm`.
- Know about `cut`, `paste`, and `join` to manipulate text files. Many people use `cut` but forget about `join`.
- Know about `wc` to count newlines (`-l`), characters (`-m`), words (`-w`) and bytes (`-c`).
- Know about `tee` to copy from stdin to a file and also to stdout, as in `ls -al | tee file.txt`.
- For more complex calculations, including grouping, reversing fields, and statistical calculations, consider [`datamash`](https://www.gnu.org/software/datamash/).
- Know that locale affects a lot of command line tools in subtle ways, including sorting order (collation) and performance. Most Linux installations will set `LANG` or other locale variables to a local setting like US English. But be aware sorting will change if you change locale. And know i18n routines can make sort or other commands run *many times* slower. In some situations (such as the set operations or uniqueness operations below) you can safely ignore slow i18n routines entirely and use traditional byte-based sort order, using `export LC_ALL=C`.
- You can set a specific command's environment by prefixing its invocation with the environment variable settings, as in `TZ=Pacific/Fiji date`.
- Know basic `awk` and `sed` for simple data munging. See [One-liners](#one-liners) for examples.
- To replace all occurrences of a string in place, in one or more files:
```sh
perl -pi.bak -e 's/old-string/new-string/g' my-files-*.txt
```
- To rename multiple files and/or search and replace within files, try [`repren`](https://github.com/jlevy/repren). (In some cases the `rename` command also allows multiple renames, but be careful as its functionality is not the same on all Linux distributions.)
```sh
# Full rename of filenames, directories, and contents foo -> bar:
repren --full --preserve-case --from foo --to bar .
# Recover backup files whatever.bak -> whatever:
repren --renames --from '(.*)\.bak' --to '\1' *.bak
# Same as above, using rename, if available:
rename 's/\.bak$//' *.bak
```
- As the man page says, `rsync` really is a fast and extraordinarily versatile file copying tool. It's known for synchronizing between machines but is equally useful locally. When security restrictions allow, using `rsync` instead of `scp` allows recovery of a transfer without restarting from scratch. It also is among the [fastest ways](https://web.archive.org/web/20130929001850/http://linuxnote.net/jianingy/en/linux/a-fast-way-to-remove-huge-number-of-files.html) to delete large numbers of files:
```sh
mkdir empty && rsync -r --delete empty/ some-dir && rmdir some-dir
```
- For monitoring progress when processing files, use [`pv`](http://www.ivarch.com/programs/pv.shtml), [`pycp`](https://github.com/dmerejkowsky/pycp), [`pmonitor`](https://github.com/dspinellis/pmonitor), [`progress`](https://github.com/Xfennec/progress), `rsync --progress`, or, for block-level copying, `dd status=progress`.
- Use `shuf` to shuffle or select random lines from a file.
- Know `sort`'s options. For numbers, use `-n`, or `-h` for handling human-readable numbers (e.g. from `du -h`). Know how keys work (`-t` and `-k`). In particular, watch out that you need to write `-k1,1` to sort by only the first field; `-k1` means sort according to the whole line. Stable sort (`sort -s`) can be useful. For example, to sort first by field 2, then secondarily by field 1, you can use `sort -k1,1 | sort -s -k2,2`.
- If you ever need to write a tab literal in a command line in Bash (e.g. for the -t argument to sort), press **ctrl-v** **[Tab]** or write `$'\t'` (the latter is better as you can copy/paste it).
- The standard tools for patching source code are `diff` and `patch`. See also `diffstat` for summary statistics of a diff and `sdiff` for a side-by-side diff. Note `diff -r` works for entire directories. Use `diff -r tree1 tree2 | diffstat` for a summary of changes. Use `vimdiff` to compare and edit files.
- For binary files, use `hd`, `hexdump` or `xxd` for simple hex dumps and `bvi`, `hexedit` or `biew` for binary editing.
- Also for binary files, `strings` (plus `grep`, etc.) lets you find bits of text.
- For binary diffs (delta compression), use `xdelta3`.
- To convert text encodings, try `iconv`. Or `uconv` for more advanced use; it supports some advanced Unicode things. For example:
```sh
# Displays hex codes or actual names of characters (useful for debugging):
uconv -f utf-8 -t utf-8 -x '::Any-Hex;' < input.txt
uconv -f utf-8 -t utf-8 -x '::Any-Name;' < input.txt
# Lowercase and removes all accents (by expanding and dropping them):
uconv -f utf-8 -t utf-8 -x '::Any-Lower; ::Any-NFD; [:Nonspacing Mark:] >; ::Any-NFC;' < input.txt > output.txt
```
- To split files into pieces, see `split` (to split by size) and `csplit` (to split by a pattern).
- Date and time: To get the current date and time in the helpful [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, use `date -u +"%Y-%m-%dT%H:%M:%SZ"` (other options [are](https://stackoverflow.com/questions/7216358/date-command-on-os-x-doesnt-have-iso-8601-i-option) [problematic](https://unix.stackexchange.com/questions/164826/date-command-iso-8601-option)). To manipulate date and time expressions, use `dateadd`, `datediff`, `strptime` etc. from [`dateutils`](http://www.fresse.org/dateutils/).
- Use `zless`, `zmore`, `zcat`, and `zgrep` to operate on compressed files.
- File attributes are settable via `chattr` and offer a lower-level alternative to file permissions. For example, to protect against accidental file deletion the immutable flag: `sudo chattr +i /critical/directory/or/file`
- Use `getfacl` and `setfacl` to save and restore file permissions. For example:
```sh
getfacl -R /some/path > permissions.txt
setfacl --restore=permissions.txt
```
- To create empty files quickly, use `truncate` (creates [sparse file](https://en.wikipedia.org/wiki/Sparse_file)), `fallocate` (ext4, xfs, btrfs and ocfs2 filesystems), `xfs_mkfile` (almost any filesystems, comes in xfsprogs package), `mkfile` (for Unix-like systems like Solaris, Mac OS).
## System debugging
- For web debugging, `curl` and `curl -I` are handy, or their `wget` equivalents, or the more modern [`httpie`](https://github.com/jkbrzt/httpie).
- To know current cpu/disk status, the classic tools are `top` (or the better `htop`), `iostat`, and `iotop`. Use `iostat -mxz 15` for basic CPU and detailed per-partition disk stats and performance insight.
- For network connection details, use `netstat` and `ss`.
- For a quick overview of what's happening on a system, `dstat` is especially useful. For broadest overview with details, use [`glances`](https://github.com/nicolargo/glances).
- To know memory status, run and understand the output of `free` and `vmstat`. In particular, be aware the "cached" value is memory held by the Linux kernel as file cache, so effectively counts toward the "free" value.
- Java system debugging is a different kettle of fish, but a simple trick on Oracle's and some other JVMs is that you can run `kill -3 <pid>` and a full stack trace and heap summary (including generational garbage collection details, which can be highly informative) will be dumped to stderr/logs. The JDK's `jps`, `jstat`, `jstack`, `jmap` are useful. [SJK tools](https://github.com/aragozin/jvm-tools) are more advanced.
- Use [`mtr`](http://www.bitwizard.nl/mtr/) as a better traceroute, to identify network issues.
- For looking at why a disk is full, [`ncdu`](https://dev.yorhel.nl/ncdu) saves time over the usual commands like `du -sh *`.
- To find which socket or process is using bandwidth, try [`iftop`](http://www.ex-parrot.com/~pdw/iftop/) or [`nethogs`](https://github.com/raboof/nethogs).
- The `ab` tool (comes with Apache) is helpful for quick-and-dirty checking of web server performance. For more complex load testing, try `siege`.
- For more serious network debugging, [`wireshark`](https://wireshark.org/), [`tshark`](https://www.wireshark.org/docs/wsug_html_chunked/AppToolstshark.html), or [`ngrep`](http://ngrep.sourceforge.net/).
- Know about `strace` and `ltrace`. These can be helpful if a program is failing, hanging, or crashing, and you don't know why, or if you want to get a general idea of performance. Note the profiling option (`-c`), and the ability to attach to a running process (`-p`). Use trace child option (`-f`) to avoid missing important calls.
- Know about `ldd` to check shared libraries etc — but [never run it on untrusted files](http://www.catonmat.net/blog/ldd-arbitrary-code-execution/).
- Know how to connect to a running process with `gdb` and get its stack traces.
- Use `/proc`. It's amazingly helpful sometimes when debugging live problems. Examples: `/proc/cpuinfo`, `/proc/meminfo`, `/proc/cmdline`, `/proc/xxx/cwd`, `/proc/xxx/exe`, `/proc/xxx/fd/`, `/proc/xxx/smaps` (where `xxx` is the process id or pid).
- When debugging why something went wrong in the past, [`sar`](http://sebastien.godard.pagesperso-orange.fr/) can be very helpful. It shows historic statistics on CPU, memory, network, etc.
- For deeper systems and performance analyses, look at `stap` ([SystemTap](https://sourceware.org/systemtap/wiki)), [`perf`](https://en.wikipedia.org/wiki/Perf_%28Linux%29), and [`sysdig`](https://github.com/draios/sysdig).
- Check what OS you're on with `uname` or `uname -a` (general Unix/kernel info) or `lsb_release -a` (Linux distro info).
- Use `dmesg` whenever something's acting really funny (it could be hardware or driver issues).
- If you delete a file and it doesn't free up expected disk space as reported by `du`, check whether the file is in use by a process:
`lsof | grep deleted | grep "filename-of-my-big-file"`
## One-liners
A few examples of piecing together commands:
- It is remarkably helpful sometimes that you can do set intersection, union, and difference of text files via `sort`/`uniq`. Suppose `a` and `b` are text files that are already uniqued. This is fast, and works on files of arbitrary size, up to many gigabytes. (Sort is not limited by memory, though you may need to use the `-T` option if `/tmp` is on a small root partition.) See also the note about `LC_ALL` above and `sort`'s `-u` option (left out for clarity below).
```sh
sort a b | uniq > c # c is a union b
sort a b | uniq -d > c # c is a intersect b
sort a b b | uniq -u > c # c is set difference a - b
```
- Pretty-print two JSON files, normalizing their syntax, then coloring and paginating the result:
```
diff <(jq --sort-keys . < file1.json) <(jq --sort-keys . < file2.json) | colordiff | less -R
```
- Use `grep . *` to quickly examine the contents of all files in a directory (so each line is paired with the filename), or `head -100 *` (so each file has a heading). This can be useful for directories filled with config settings like those in `/sys`, `/proc`, `/etc`.
- Summing all numbers in the third column of a text file (this is probably 3X faster and 3X less code than equivalent Python):
```sh
awk '{ x += $3 } END { print x }' myfile
```
- To see sizes/dates on a tree of files, this is like a recursive `ls -l` but is easier to read than `ls -lR`:
```sh
find . -type f -ls
```
- Say you have a text file, like a web server log, and a certain value that appears on some lines, such as an `acct_id` parameter that is present in the URL. If you want a tally of how many requests for each `acct_id`:
```sh
egrep -o 'acct_id=[0-9]+' access.log | cut -d= -f2 | sort | uniq -c | sort -rn
```
- To continuously monitor changes, use `watch`, e.g. check changes to files in a directory with `watch -d -n 2 'ls -rtlh | tail'` or to network settings while troubleshooting your wifi settings with `watch -d -n 2 ifconfig`.
- Run this function to get a random tip from this document (parses Markdown and extracts an item):
```sh
function taocl() {
curl -s https://raw.githubusercontent.com/jlevy/the-art-of-command-line/master/README.md |
sed '/cowsay[.]png/d' |
pandoc -f markdown -t html |
xmlstarlet fo --html --dropdtd |
xmlstarlet sel -t -v "(html/body/ul/li[count(p)>0])[$RANDOM mod last()+1]" |
xmlstarlet unesc | fmt -80 | iconv -t US
}
```
## Obscure but useful
- `expr`: perform arithmetic or boolean operations or evaluate regular expressions
- `m4`: simple macro processor
- `yes`: print a string a lot
- `cal`: nice calendar
- `env`: run a command (useful in scripts)
- `printenv`: print out environment variables (useful in debugging and scripts)
- `look`: find English words (or lines in a file) beginning with a string
- `cut`, `paste` and `join`: data manipulation
- `fmt`: format text paragraphs
- `pr`: format text into pages/columns
- `fold`: wrap lines of text
- `column`: format text fields into aligned, fixed-width columns or tables
- `expand` and `unexpand`: convert between tabs and spaces
- `nl`: add line numbers
- `seq`: print numbers
- `bc`: calculator
- `factor`: factor integers
- [`gpg`](https://gnupg.org/): encrypt and sign files
- `toe`: table of terminfo entries
- `nc`: network debugging and data transfer
- `socat`: socket relay and tcp port forwarder (similar to `netcat`)
- [`slurm`](https://github.com/mattthias/slurm): network traffic visualization
- `dd`: moving data between files or devices
- `file`: identify type of a file
- `tree`: display directories and subdirectories as a nesting tree; like `ls` but recursive
- `stat`: file info
- `time`: execute and time a command
- `timeout`: execute a command for specified amount of time and stop the process when the specified amount of time completes.
- `lockfile`: create semaphore file that can only be removed by `rm -f`
- `logrotate`: rotate, compress and mail logs.
- `watch`: run a command repeatedly, showing results and/or highlighting changes
- [`when-changed`](https://github.com/joh/when-changed): runs any command you specify whenever it sees file changed. See `inotifywait` and `entr` as well.
- `tac`: print files in reverse
- `comm`: compare sorted files line by line
- `strings`: extract text from binary files
- `tr`: character translation or manipulation
- `iconv` or `uconv`: conversion for text encodings
- `split` and `csplit`: splitting files
- `sponge`: read all input before writing it, useful for reading from then writing to the same file, e.g., `grep -v something some-file | sponge some-file`
- `units`: unit conversions and calculations; converts furlongs per fortnight to twips per blink (see also `/usr/share/units/definitions.units`)
- `apg`: generates random passwords
- `xz`: high-ratio file compression
- `ldd`: dynamic library info
- `nm`: symbols from object files
- `ab` or [`wrk`](https://github.com/wg/wrk): benchmarking web servers
- `strace`: system call debugging
- [`mtr`](http://www.bitwizard.nl/mtr/): better traceroute for network debugging
- `cssh`: visual concurrent shell
- `rsync`: sync files and folders over SSH or in local file system
- [`wireshark`](https://wireshark.org/) and [`tshark`](https://www.wireshark.org/docs/wsug_html_chunked/AppToolstshark.html): packet capture and network debugging
- [`ngrep`](http://ngrep.sourceforge.net/): grep for the network layer
- `host` and `dig`: DNS lookups
- `lsof`: process file descriptor and socket info
- `dstat`: useful system stats
- [`glances`](https://github.com/nicolargo/glances): high level, multi-subsystem overview
- `iostat`: Disk usage stats
- `mpstat`: CPU usage stats
- `vmstat`: Memory usage stats
- `htop`: improved version of top
- `last`: login history
- `w`: who's logged on
- `id`: user/group identity info
- [`sar`](http://sebastien.godard.pagesperso-orange.fr/): historic system stats
- [`iftop`](http://www.ex-parrot.com/~pdw/iftop/) or [`nethogs`](https://github.com/raboof/nethogs): network utilization by socket or process
- `ss`: socket statistics
- `dmesg`: boot and system error messages
- `sysctl`: view and configure Linux kernel parameters at run time
- `hdparm`: SATA/ATA disk manipulation/performance
- `lsblk`: list block devices: a tree view of your disks and disk partitions
- `lshw`, `lscpu`, `lspci`, `lsusb`, `dmidecode`: hardware information, including CPU, BIOS, RAID, graphics, devices, etc.
- `lsmod` and `modinfo`: List and show details of kernel modules.
- `fortune`, `ddate`, and `sl`: um, well, it depends on whether you consider steam locomotives and Zippy quotations "useful"
## macOS only
These are items relevant *only* on macOS.
- Package management with `brew` (Homebrew) and/or `port` (MacPorts). These can be used to install on macOS many of the above commands.
- Copy output of any command to a desktop app with `pbcopy` and paste input from one with `pbpaste`.
- To enable the Option key in macOS Terminal as an alt key (such as used in the commands above like **alt-b**, **alt-f**, etc.), open Preferences -> Profiles -> Keyboard and select "Use Option as Meta key".
- To open a file with a desktop app, use `open` or `open -a /Applications/Whatever.app`.
- Spotlight: Search files with `mdfind` and list metadata (such as photo EXIF info) with `mdls`.
- Be aware macOS is based on BSD Unix, and many commands (for example `ps`, `ls`, `tail`, `awk`, `sed`) have many subtle variations from Linux, which is largely influenced by System V-style Unix and GNU tools. You can often tell the difference by noting a man page has the heading "BSD General Commands Manual." In some cases GNU versions can be installed, too (such as `gawk` and `gsed` for GNU awk and sed). If writing cross-platform Bash scripts, avoid such commands (for example, consider Python or `perl`) or test carefully.
- To get macOS release information, use `sw_vers`.
## Windows only
These items are relevant *only* on Windows.
### Ways to obtain Unix tools under Windows
- Access the power of the Unix shell under Microsoft Windows by installing [Cygwin](https://cygwin.com/). Most of the things described in this document will work out of the box.
- On Windows 10, you can use [Windows Subsystem for Linux (WSL)](https://msdn.microsoft.com/commandline/wsl/about), which provides a familiar Bash environment with Unix command line utilities.
- If you mainly want to use GNU developer tools (such as GCC) on Windows, consider [MinGW](http://www.mingw.org/) and its [MSYS](http://www.mingw.org/wiki/msys) package, which provides utilities such as bash, gawk, make and grep. MSYS doesn't have all the features compared to Cygwin. MinGW is particularly useful for creating native Windows ports of Unix tools.
- Another option to get Unix look and feel under Windows is [Cash](https://github.com/dthree/cash). Note that only very few Unix commands and command-line options are available in this environment.
### Useful Windows command-line tools
- You can perform and script most Windows system administration tasks from the command line by learning and using `wmic`.
- Native command-line Windows networking tools you may find useful include `ping`, `ipconfig`, `tracert`, and `netstat`.
- You can perform [many useful Windows tasks](http://www.thewindowsclub.com/rundll32-shortcut-commands-windows) by invoking the `Rundll32` command.
### Cygwin tips and tricks
- Install additional Unix programs with the Cygwin's package manager.
- Use `mintty` as your command-line window.
- Access the Windows clipboard through `/dev/clipboard`.
- Run `cygstart` to open an arbitrary file through its registered application.
- Access the Windows registry with `regtool`.
- Note that a `C:\` Windows drive path becomes `/cygdrive/c` under Cygwin, and that Cygwin's `/` appears under `C:\cygwin` on Windows. Convert between Cygwin and Windows-style file paths with `cygpath`. This is most useful in scripts that invoke Windows programs.
## More resources
- [awesome-shell](https://github.com/alebcay/awesome-shell): A curated list of shell tools and resources.
- [awesome-osx-command-line](https://github.com/herrbischoff/awesome-osx-command-line): A more in-depth guide for the macOS command line.
- [Strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/) for writing better shell scripts.
- [shellcheck](https://github.com/koalaman/shellcheck): A shell script static analysis tool. Essentially, lint for bash/sh/zsh.
- [Filenames and Pathnames in Shell](http://www.dwheeler.com/essays/filenames-in-shell.html): The sadly complex minutiae on how to handle filenames correctly in shell scripts.
- [Data Science at the Command Line](http://datascienceatthecommandline.com/#tools): More commands and tools helpful for doing data science, from the book of the same name

View File

@@ -0,0 +1,54 @@
---
title: Linux Keyboard Shortcuts
created: '2025-06-29T16:45:05.400Z'
modified: '2025-06-29T16:45:10.372Z'
---
## Linux Keyboard Shortcuts
| **Key** | **Function** |
| :--: | :-- |
| **Cursor Movement** |
| Ctrl+B | Move cursor backward one character position |
| Ctrl+F | Move cursor forward one character position |
| Alt+F | Move cursor one word forward in line |
| Alt+B | Move cursor one word backward in line |
| Ctrl+A | Move cursor to beginning of text in line |
| Ctrl+E | Move cursor to end of text in line |
| **Text Editing** |
| Ctrl+D | Erase character forward from cursor left to right |
| Ctrl+H | Erase character backward from cursor right to left |
| Alt+D | Erase the next word from cursor left to right |
| Ctrl+W | Erase backwards to first non-alphanumeric character or empty space |
| Ctrl+U | Erase a line of input from cursor right to left |
| Ctrl+K | Erase a line of input from cursor left to right |
| Alt+R | Revert any changes to a previously executed command that's being edited |
| Alt+. | Fetch and paste the last word at end of a command from previous commands |
| Ctrl+T | Reverse the position of the character the cursor is on with the previous character |
| Alt+T | Reverse the position of the word the cursor is in with the previous word |
| Alt+U | Capitalize every character from cursor left to right to the end of one word |
| Alt+L | Uncapitalize every character from cursor left to right to the end of one word |
| Ctrl+Y | Paste (yank) text cut by Ctrl+U, Ctrl+K, or Ctrl+W |
| Ctrl+_ | Undo last change |
| **Command History** |
| Ctrl+P | Fetch previous command from history list |
| Ctrl+N | Fetch next command from history list |
| Ctrl+R | Reverse search commands from history list |
| **Process Control** |
| Ctrl+C | Break/Terminate a foreground job |
| Ctrl+Z | Suspend a foreground job |
| Ctrl+S | Suspend output to screen |
| Ctrl+Q | Resume output to screen |
| **Terminal Control** |
| Ctrl+L | Clear screen contents (command-line needs to be empty) |
| Ctrl+D | Log out from a shell (similar to exit) or send EOF |
| Ctrl+O | Accept the current line for execution and fetch the next command |
| Ctrl+X (twice) | Toggle cursor between current position and beginning of the line |
| **Text Editing (Terminal)** |
| Ctrl+Shift+C | Copy |
| Ctrl+Shift+V | Paste |
| Shift+Insert | Paste (alternative) |

View File

@@ -0,0 +1,73 @@
---
title: Linux Special Characters
created: '2025-06-29T16:35:54.601Z'
modified: '2025-06-29T16:50:23.796Z'
---
## Linux Special Characters
> **Note** 💡<br>
> This symbol "└─>" represents an alternative meaning of some characters.
| Char.&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| Description |
| --- | --- |
| ~ | Home directory [tilde]. The path to a user's home directory location. |
| - | Last directory [hyphen]. Go to the previously chosen directory. |
| └─> | Option flag for a command or filter. |
| └─> | Arithmetic operator. Minus of arithmetic operations. |
| / | Root directory [forward slash]. The path to root directory location. |
| └─> | Filename path separator. |
| \ | Escape [backslash]. A quoting mechanism for single characters. It preserves the literal value of the next character that follows, with the exception of newline. |
| └─> | Arithmetic operator. Divider of arithmetic operations. |
| \| | Pipe. This is a method of chaining commands together. Connects the output (stdout) of command1 to the input (stdin) of command2. Each command reads the previous command’s output. |
| \|& | This operator connects the output (stdout) and error (stderr) of command1 to the input (stdin) of command2. |
| \|\| | The OR operator is used to chain commands. It will execute the first command then stop if successful, if not, it will proceed pass failed commands until one is successful and stop. |
| && | The AND operator is used to chain commands. It will execute commands only if the first command is successful and proceed until one fails. |
| \; | Command separator [semicolon]. Used to separate multiple commands and output all successful and failed ones. |
| & | Run job in background [and]. A command followed by an & will run in the background. |
| >, >>, < | Redirect a command's standard output (stdout) or input (stdin) into a file. |
| &>, >& | Redirects a command's both standard output (stdout) and error (stderr) into a file. |
| <&- | Close standard input (stdin) to prevent showing from a file. |
| >&- | Close standard output (stdout) to prevent showing from a file. |
| >| | Force redirection (even if the noclobber option is set). This will forcibly overwrite an existing file. |
| " | Partial quoting [double quotes]. Protects the text inside them from being split into multiple words or arguments, yet allow substitutions to occur, meaning most other special characters is usually prevented. |
| . | Source command [period]. To evaluate commands in the current execution context. This is a bash builtin. |
| └─> | "As a component of a filename. When working with filenames, a leading dot is the prefix of a "hidden" file, a file that an ls will not normally show. |
| └─> | Character match. When matching characters, as part of a regular expression, a "dot" matches a single character. |
| ' | Full quoting [single quotes]. Protects the text inside them so that it has a literal meaning. This is a stronger form of quoting than double quotes. |
| ` | Command substitution [backquotes]. Assign the output of a shell command to a variable. |
| # | Comment [number sign]. Lines in files beginning with a # (with the exception of #!) are comments and will not be executed. |
| ! | Reverse (or negate) [exclamation]. The ! operator inverts the exit status of the command to which it is applied. It also inverts the meaning of a test operator. |
| * | Wild card [asterisk]. The * character serves as a "wild card" for filename expansion in globbing. By itself, it matches every filename in a given directory. |
| └─> | Arithmetic operator. Multiplier of arithmetic operations. |
| ? | Wild card [question mark]. The ? character serves as a single-character "wild card" for filename expansion in globbing, as well as representing one character in an extended regular expression. |
| └─> | Test operator. Within certain expressions, the ? indicates a test for a condition. |
| { } | Inline group [curly brackets]. Commands inside the curly braces are treated as if they were one command. |
| └─> | Placeholder for output text. |
| ( ) | Subshell group [parentheses]. Commands within are executed in a subshell (a new process) Used much like a sandbox, if a command causes side effects (like changing variables), it will have no effect on the current shell. |
| [ ] | Test expression [brackets]. It is part of the shell builtin test. |
| └─> | Array element. Brackets set off the numbering of each element. |
| └─> | Range of characters. As part of a regular expression, brackets delineate a range of characters to match. |
| \[\[ \]\] | Test/Evaluate [double brackets] a condition expression to determine whether true or false. It is more flexible than the single-bracket [ ] test. |
| (( )) | Arithmetic expression [double parentheses]. Characters such as +, -, *, and / are mathematical operators used for calculations. |
| ~+ | Current working directory. |
| ~- | Previous working directory. |
| : | Null command [colon]. This is the shell equivalent of a "NOP" (no op, a do-nothing operation). It may be considered a synonym for the shell builtin true. |
| ;; | Terminator [double semicolon]. Only used in case constructs to indicate the end of an alternative. |
| " " | Whitespace. This is a tab, newline, vertical tab, form feed, carriage return, or space. Bash uses whitespace to determine where words begin and end. |
| ,, , | Lowercase conversion in parameter substitution. |
| ^, ^^ | Uppercase conversion in parameter substitution. |
| $ | Variable substitution. A $ prefixing a variable name indicates the value the variable holds |
| └─> | End-of-line. In a regular expression, a "$" addresses the end of a line of text. |
| $* | All the arguments are seen as a single word. |
| !! | The previous command. |
| !$ | The last argument to the previous command. |
| !* | All the arguments from the previous command. |
| $? | The exit status of the last command executed. |
| $# | The number of arguments supplied to a script. |
| $$ | The process number of the current shell. For shell scripts, this is the process ID under which they are executing. |
| $! | The process number of the last background command. |
| $_ | Special variable set to final argument of previous command executed. |
| $- | Expands to the current option flags as specified upon invocation, by the set builtin command, or those set by the shell itself (such as the -i option). |
| $0 | Used to reference the name of the current shell or current shell script. |
| $n | These variables correspond to the arguments with which a script was invoked. Here n is a positive decimal number corresponding to the position of an argument (the first argument is $1, the second argument is $2, and so on). |