This section will explain the basic commands in BASH when using a Linux CLI. It will also help with navigating your way through the file system and explain scripting.
ECHO - Text back to you
VIM is a good text and file editor for Linux
vim (file name) enter
:w writes the file, q to quit
use :wq to write file and quit at the same time
To quit without making changes use :q! while in the file
To read your file, use cat (filename)
To exit edit mode after writing your file while in VIM, hit the esc key to use console to write and exit file
CHMOD - modifies permissions for a file
Type chmod u+x (file name) to give the owner permissions
LESS: gives you one page at a time when opening a file
FIND: Will help you find something is a directory
Example: find / -name "filename*"
AWK: Used for precise seeking in a file and as output filtering
awk '{print $1}' file.txt
awk -F, '{print $2}' data.csv
SED: A command line tool to modify values in a text file using regular expressions
sed 's/foo/bar/' file.txt
sed 's/foo/bar/g' file.txt
TMUX: Creates another session
Example:
tmux new -s name create session
tmux ls list sessions
tmux attach -t name attach session
Ctrl+b d detach
Ctrl+b c new window
Ctrl+b % vertical split
Ctrl+b " horizontal split
Ctrl+b arrow move pane
Ctrl+b n next window
SSH: A tool to access your linux machine remotely.
Type: username@machineIP then accept user fingerprints and then enter your password
TOP/HTOP: A list of the processes running on your machine
TOP lists all process
HTOP puts it in a more organized way
Other Useful Commands:
command './(filename)' runs the file
command 'ls' is a list command to see files and directories
command 'grep' filters out everything except the word that follows grep
Using "" can feed a string into a command
FLOW CONTROL
if/elif/else statements:
Basic Concept:
if condition1
run block
else if condition2
run block
else
fallback
Example:
if [ $score -ge 90 ]; then
echo "Grade A"
elif [ $score -ge 80 ]; then
echo "Grade B"
else
echo "Grade C"
fi
VARIABLES
Fundamental for passing information between commands and making scripts more dynamic.
No spaces around '='
Variable expansion:
variable=value
Example:
name="Alice"
echo $name
Output = Alice
COMMMAND SUBSTITUTION
Command substitution runs a command and replaces the command itself with its output.
$(command)
Example:
echo "Today is $(date)"
Output: Today is Tue Mar 10 12:30:00 PDT
current_dir=$(pwd)
echo "You are in $current_dir"
*Command substitution allows Bash scripts to treat the command output as data.
10 essential Bash scripts where command substitution is essential:
1. Timestamped Backup File
backup="database_$(date +%Y-%m-%d).sql"
cp database.sql "$backup"
2. Count Files in a Directory
file_count=$(ls | wc -l)
echo "There are $file_count files in this directory."
3. Detect Current User
current_user=$(whoami)
echo "Running script as $current_user"
4. Get System Uptime
uptime_info=$(uptime)
echo "System status: $uptime_info"
5. Find the Largest File
largest=$(ls -S | head -n 1)
echo "Largest file: $largest"
6. Count Errors in a Log File
errors=$(grep -c "ERROR" app.log)
echo "Error count: $errors"
7. Create a Dynamic Directory Name
project_dir="project_$(date +%s)"
mkdir "$project_dir"
8. Get Current Git Branch
branch=$(git branch --show-current)
echo "Current branch: $branch"
9. Get System IP Address
ip=$(hostname -I)
echo "Server IP: $ip"
10. Check Disk Usage
usage=$(df / | tail -1 | awk '{print $5}')
echo "Disk usage: $usage"
REDIRECTION
Redirection in Bash lets you control where command input comes from and where output goes. You can send output to files, read from files, or connect commands together by using redirection features in Bash.
Using '>' symbol moves a command or echo into a file
ex: Hello World! > hello.txt moves the echo into the hello.txt file
Using one '>' will overwrite what was previously written in that file. Use '>>' to ADD contents to the file
command > file # stdout to file (overwrite)
command >> file # stdout to file (append)
command < file # file to stdin
command > file # stderr to file
command > file 2>&1 # stdout + stderr to file
command > /dev/null # discard output
command | command # pipe output to next command
EXIT CODES
Exit codes (also called exit statuses or return codes) tell the shell whether a command succeeded or failed. Every command in Bash finishes with a numeric code that scripts can check to decide what to do next.
When a command finishes, it returns a number between 0 and 255
0 = success
non-zero = failure
5 Common Exit Codes:
0 success
1 general error
2 misuse of shell command
126 command cannot execute
127 command not found
STRING MANIPULATION
Strings in Bash are just variables containing text.
Quick String Manipulation Cheat Sheet:
${#var} # string length
${var:0:5} # substring
${var#pattern} # remove prefix (short)
${var##pattern} # remove prefix (long)
${var%pattern} # remove suffix (short)
${var%%pattern} # remove suffix (long)
${var/pat/repl} # replace first match
${var//pat/repl} # replace all matches
${var^^} # uppercase
${var,,} # lowercase
${var:-default} # default value
${var:=default} # assign default
Example:
path="/home/user/report.txt"
filename=${path##*/}
echo "$filename"
Output: report.txt
DIRECTORY TREE STRUCTURE
Directory tree structure is essential when working in Bash because the shell navigates and manipulates files based on the system's hierachical filesystem and can be easy to get lost when trying to navigate in a CLI.
Conceptually looks like this:
/
├── bin
├── etc
├── home
│ ├── alice
│ └── bob
├── usr
└── var
Root directory: /
Example:
cd /
ls
This shows the top-level directories of the system.
To check the current directory you are in: pwd
The command 'cd' is used to move to a directory
Example: cd /home/user
cd Documents - Moves you into that directory
cd .. - moves you to parent directory
Quick Directory List:
- pwd # show current directory
- ls # list directory contents
- cd directory # change directory
- cd .. # move to parent
- cd ~ # go to home directory
- mkdir dir # create directory
- mkdir -p a/b/c # create nested directories
- rm -r dir # remove directory recursively
- ls -R # recursive listing
- ls -a # show hidden files
RELATIVE PATHS
Relative paths in Bash are ways to refer to files or directories based on your current location in the filesystem, instead of specifying the full (absolute) path.
- . # current directory
- .. # parent directory
- ../.. # grandparent directory
- folder/file.txt # file inside subfolder
- ../file.txt # file in parent folder
- ./file.txt # file in current folder
FILE SYSTEM HIERARCHY
- /bin - Essential command binaries
- /etc - Configuration files
- /home - User directories
- /usr - Applications and libraries
- /var - Logs and variable data
- /tmp - Temporary files
1. Cursor Movement
Move around the command line quickly.
| Shortcut | What it does |
|---|---|
| Ctrl + A | Move cursor to the start of the line |
| Ctrl + E | Move cursor to the end of the line |
| Alt + B | Move back one word |
| Alt + F | Move forward one word |
2. Editing Text
Quickly delete or edit parts of your command.
| Shortcut | What it does |
|---|---|
| Ctrl + U | Delete from cursor to start of line |
| Ctrl + K | Delete from cursor to end of line |
| Ctrl + W | Delete previous word |
| Alt + D | Delete next word |
| Ctrl + Y | Paste last deleted text |
3. Command History
Reuse previous commands.
| Shortcut | What it does |
|---|---|
| Ctrl + P | Previous command |
| Ctrl + N | Next command |
| Ctrl + R | Search command history |
| Ctrl + G | Exit history search |
| !! | Run last command again |
Example:
sudo !!
Runs the previous command with sudo.
4. Screen / Process Control
| Shortcut | What it does |
|---|---|
| Ctrl + C | Cancel running command |
| Ctrl + Z | Suspend process |
| Ctrl + D | Exit terminal / send EOF |
| Ctrl + L | Clear the screen |
5. Tab Completion (Very Useful)
| Shortcut | What it does |
|---|---|
| Tab | Auto-complete commands, files, directories |
| Tab Tab | Show all possible completions |
Example:
cd Doc<Tab>
Auto-completes to documents
Ctrl + R is one of the most powerful shortcuts. You can start typing part of a previous command and Bash will find it instantly.
Example:
Ctrl + R
git
It searches your history for commands containing git.