Linux Shell Commands: Complete Guide for Beginners & Pros

Master Linux shell commands with this comprehensive guide covering navigation, file operations, permissions, process management, and advanced tips.

Linux Shell Commands: Complete Guide

Table of Contents

1. [Introduction to Linux Shell](#introduction-to-linux-shell) 2. [Basic Navigation Commands](#basic-navigation-commands) 3. [File and Directory Operations](#file-and-directory-operations) 4. [File Content Operations](#file-content-operations) 5. [File Permissions and Ownership](#file-permissions-and-ownership) 6. [Process Management](#process-management) 7. [System Information Commands](#system-information-commands) 8. [Text Processing Commands](#text-processing-commands) 9. [Network Commands](#network-commands) 10. [Archive and Compression](#archive-and-compression) 11. [Command Line Tips and Tricks](#command-line-tips-and-tricks)

Introduction to Linux Shell

The Linux shell is a command-line interface that allows users to interact with the operating system through text commands. It serves as an intermediary between the user and the kernel, interpreting commands and executing them accordingly. The most common shell in Linux distributions is Bash (Bourne Again Shell), though other shells like Zsh, Fish, and Dash are also available.

Shell Basics

When you open a terminal, you are presented with a prompt that typically shows: - Username - Hostname - Current directory - Prompt symbol ($ for regular users, # for root)

Example prompt: user@hostname:~$

The tilde (~) represents the user's home directory, and the dollar sign ($) indicates you are logged in as a regular user.

Basic Navigation Commands

Navigation is fundamental to working with the Linux command line. These commands help you move around the filesystem and understand your current location.

pwd - Print Working Directory

The pwd command displays the absolute path of your current directory.

Syntax: `bash pwd [OPTION] `

Options: | Option | Description | |--------|-------------| | -L | Display logical current directory (default) | | -P | Display physical current directory (resolve symbolic links) |

Examples: `bash pwd

Output: /home/username

pwd -P

Output: /home/username (resolves any symbolic links)

`

Notes: - Always shows the full path from the root directory (/) - Useful when you are lost in the directory structure - Essential for scripting when you need to know the current location

ls - List Directory Contents

The ls command lists files and directories in the current or specified directory.

Syntax: `bash ls [OPTION] [FILE/DIRECTORY] `

Common Options: | Option | Description | |--------|-------------| | -l | Long format (detailed information) | | -a | Show hidden files (starting with .) | | -h | Human-readable file sizes | | -t | Sort by modification time | | -r | Reverse order | | -R | Recursive listing | | -d | List directories themselves, not contents |

Examples: `bash ls

Output: file1.txt file2.txt directory1

ls -l

Output:

-rw-r--r-- 1 user group 1024 Jan 15 10:30 file1.txt

drwxr-xr-x 2 user group 4096 Jan 15 10:25 directory1

ls -la

Shows all files including hidden ones with detailed information

ls -lh

Shows file sizes in human-readable format (KB, MB, GB)

ls -lt

Lists files sorted by modification time (newest first)

ls *.txt

Lists all files ending with .txt

`

Notes: - Hidden files in Linux start with a dot (.) - The long format shows permissions, links, owner, group, size, and modification time - Color coding helps distinguish file types (directories, executables, links)

cd - Change Directory

The cd command changes your current working directory.

Syntax: `bash cd [DIRECTORY] `

Special Directory References: | Symbol | Meaning | |--------|---------| | ~ | Home directory | | . | Current directory | | .. | Parent directory | | - | Previous directory | | / | Root directory |

Examples: `bash cd /home/username

Navigate to specific directory

cd ~

Navigate to home directory

cd ..

Move up one directory level

cd ../..

Move up two directory levels

cd -

Return to previous directory

cd

Navigate to home directory (same as cd ~)

`

Notes: - Without arguments, cd takes you to your home directory - Use tab completion to avoid typing full directory names - Case-sensitive in most Linux distributions

File and Directory Operations

These commands allow you to create, copy, move, and delete files and directories.

mkdir - Create Directories

The mkdir command creates new directories.

Syntax: `bash mkdir [OPTION] DIRECTORY_NAME `

Options: | Option | Description | |--------|-------------| | -p | Create parent directories as needed | | -v | Verbose output | | -m | Set permissions |

Examples: `bash mkdir new_directory

Creates a single directory

mkdir dir1 dir2 dir3

Creates multiple directories

mkdir -p path/to/new/directory

Creates nested directories

mkdir -v test_dir

Creates directory with verbose output

mkdir -m 755 secure_dir

Creates directory with specific permissions

`

Notes: - Directory names should not contain spaces (use underscores or hyphens) - Use quotes for directory names with spaces: mkdir "my directory" - The -p option prevents errors if directories already exist

rmdir - Remove Empty Directories

The rmdir command removes empty directories only.

Syntax: `bash rmdir [OPTION] DIRECTORY `

Options: | Option | Description | |--------|-------------| | -p | Remove parent directories if they become empty | | -v | Verbose output |

Examples: `bash rmdir empty_directory

Removes an empty directory

rmdir -p path/to/empty/directory

Removes directory and empty parent directories

rmdir dir1 dir2 dir3

Removes multiple empty directories

`

touch - Create Empty Files

The touch command creates empty files or updates timestamps of existing files.

Syntax: `bash touch [OPTION] FILE `

Examples: `bash touch newfile.txt

Creates an empty file

touch file1.txt file2.txt file3.txt

Creates multiple empty files

touch -t 202301151030 oldfile.txt

Sets specific timestamp (YYYYMMDDhhmm)

`

cp - Copy Files and Directories

The cp command copies files and directories.

Syntax: `bash cp [OPTION] SOURCE DESTINATION `

Options: | Option | Description | |--------|-------------| | -r | Recursive (for directories) | | -i | Interactive (prompt before overwrite) | | -v | Verbose output | | -u | Update (copy only newer files) | | -p | Preserve attributes |

Examples: `bash cp file1.txt file2.txt

Copies file1.txt to file2.txt

cp file1.txt /path/to/destination/

Copies file to different directory

cp -r directory1 directory2

Copies directory recursively

cp -i file1.txt file2.txt

Prompts before overwriting existing file2.txt

cp *.txt backup/

Copies all .txt files to backup directory

`

mv - Move/Rename Files and Directories

The mv command moves or renames files and directories.

Syntax: `bash mv [OPTION] SOURCE DESTINATION `

Options: | Option | Description | |--------|-------------| | -i | Interactive (prompt before overwrite) | | -v | Verbose output | | -u | Update (move only newer files) |

Examples: `bash mv oldname.txt newname.txt

Renames file

mv file.txt /path/to/destination/

Moves file to different directory

mv directory1 directory2

Renames or moves directory

mv *.txt documents/

Moves all .txt files to documents directory

`

rm - Remove Files and Directories

The rm command removes files and directories.

Syntax: `bash rm [OPTION] FILE/DIRECTORY `

Options: | Option | Description | |--------|-------------| | -r | Recursive (for directories) | | -f | Force (no prompts) | | -i | Interactive (prompt for each file) | | -v | Verbose output |

Examples: `bash rm file.txt

Removes a file

rm -r directory

Removes directory and its contents

rm -rf dangerous_directory

Forcefully removes directory (use with caution)

rm *.tmp

Removes all .tmp files

rm -i *.txt

Prompts before removing each .txt file

`

Warning: The rm command permanently deletes files. There is no recycle bin in the command line.

File Content Operations

These commands help you view, edit, and manipulate file contents.

cat - Display File Contents

The cat command displays the entire contents of a file.

Syntax: `bash cat [OPTION] FILE `

Options: | Option | Description | |--------|-------------| | -n | Number lines | | -b | Number non-empty lines | | -s | Suppress multiple empty lines |

Examples: `bash cat file.txt

Displays entire file content

cat -n file.txt

Displays file with line numbers

cat file1.txt file2.txt

Displays multiple files sequentially

cat file1.txt file2.txt > combined.txt

Combines files into a new file

`

less - View File Contents Page by Page

The less command allows you to view file contents one page at a time.

Syntax: `bash less [OPTION] FILE `

Navigation Keys in less: | Key | Action | |-----|--------| | Space | Next page | | b | Previous page | | / | Search forward | | ? | Search backward | | q | Quit | | G | Go to end | | g | Go to beginning |

Examples: `bash less largefile.txt

View large file page by page

less +G file.txt

Start at end of file

command | less

Pipe command output to less

`

head - Display First Lines

The head command displays the first lines of a file.

Syntax: `bash head [OPTION] FILE `

Options: | Option | Description | |--------|-------------| | -n NUM | Show first NUM lines | | -c NUM | Show first NUM bytes |

Examples: `bash head file.txt

Shows first 10 lines (default)

head -n 5 file.txt

Shows first 5 lines

head -c 100 file.txt

Shows first 100 bytes

`

tail - Display Last Lines

The tail command displays the last lines of a file.

Syntax: `bash tail [OPTION] FILE `

Options: | Option | Description | |--------|-------------| | -n NUM | Show last NUM lines | | -f | Follow (monitor file changes) | | -c NUM | Show last NUM bytes |

Examples: `bash tail file.txt

Shows last 10 lines (default)

tail -n 20 file.txt

Shows last 20 lines

tail -f /var/log/syslog

Monitors log file for new entries

tail -f -n 50 application.log

Monitors last 50 lines of log file

`

grep - Search Text Patterns

The grep command searches for patterns in files.

Syntax: `bash grep [OPTION] PATTERN FILE `

Options: | Option | Description | |--------|-------------| | -i | Case-insensitive search | | -r | Recursive search | | -n | Show line numbers | | -v | Invert match (show non-matching lines) | | -c | Count matches | | -l | Show only filenames |

Examples: `bash grep "error" logfile.txt

Search for "error" in file

grep -i "ERROR" logfile.txt

Case-insensitive search

grep -n "function" script.py

Search with line numbers

grep -r "TODO" /path/to/project/

Recursive search in directory

grep -v "debug" logfile.txt

Show lines that don't contain "debug"

ps aux | grep apache

Search process list for apache

`

File Permissions and Ownership

Linux uses a permission system to control access to files and directories.

Understanding Permissions

Linux permissions are represented by a 10-character string: - First character: File type (- for file, d for directory, l for link) - Next 9 characters: Permissions in groups of 3 (owner, group, others)

Each group of 3 represents: - r (read): 4 - w (write): 2 - x (execute): 1

Permission Examples: | Permission | Octal | Meaning | |------------|-------|---------| | rwx | 7 | Read, write, execute | | rw- | 6 | Read, write | | r-x | 5 | Read, execute | | r-- | 4 | Read only | | -wx | 3 | Write, execute | | -w- | 2 | Write only | | --x | 1 | Execute only | | --- | 0 | No permissions |

chmod - Change File Permissions

The chmod command changes file and directory permissions.

Syntax: `bash chmod [OPTION] MODE FILE `

Examples: `bash chmod 755 script.sh

Owner: rwx, Group: r-x, Others: r-x

chmod u+x file.txt

Add execute permission for owner

chmod g-w file.txt

Remove write permission for group

chmod o=r file.txt

Set others to read-only

chmod -R 644 directory/

Recursively set permissions for directory contents

chmod a+r file.txt

Add read permission for all (owner, group, others)

`

Symbolic Mode: | Symbol | Meaning | |--------|---------| | u | User (owner) | | g | Group | | o | Others | | a | All | | + | Add permission | | - | Remove permission | | = | Set exact permission |

chown - Change File Ownership

The chown command changes file and directory ownership.

Syntax: `bash chown [OPTION] OWNER[:GROUP] FILE `

Examples: `bash chown user file.txt

Change owner to 'user'

chown user:group file.txt

Change owner to 'user' and group to 'group'

chown :group file.txt

Change only group

chown -R user:group directory/

Recursively change ownership

sudo chown root:root important_file

Change to root ownership (requires sudo)

`

Process Management

Process management commands help you monitor and control running programs.

ps - Display Running Processes

The ps command shows information about running processes.

Syntax: `bash ps [OPTION] `

Common Options: | Option | Description | |--------|-------------| | aux | All processes with detailed info | | ef | All processes in full format | | -u USER | Processes for specific user |

Examples: `bash ps

Shows processes for current user

ps aux

Shows all processes with detailed information

ps aux | grep apache

Find apache processes

ps -u username

Show processes for specific user

ps ef

Show all processes in full format

`

top - Real-time Process Monitor

The top command displays running processes in real-time.

Syntax: `bash top [OPTION] `

Interactive Keys in top: | Key | Action | |-----|--------| | q | Quit | | k | Kill process | | r | Renice process | | M | Sort by memory usage | | P | Sort by CPU usage | | h | Help |

Examples: `bash top

Display real-time process information

top -u username

Show processes for specific user

top -p PID

Monitor specific process

`

kill - Terminate Processes

The kill command sends signals to processes to terminate them.

Syntax: `bash kill [SIGNAL] PID `

Common Signals: | Signal | Number | Description | |--------|--------|-------------| | TERM | 15 | Graceful termination (default) | | KILL | 9 | Force termination | | HUP | 1 | Hang up | | STOP | 19 | Stop process | | CONT | 18 | Continue process |

Examples: `bash kill 1234

Gracefully terminate process with PID 1234

kill -9 1234

Force kill process with PID 1234

kill -TERM 1234

Send TERM signal (same as default)

killall firefox

Kill all firefox processes

pkill -f "python script.py"

Kill processes matching pattern

`

System Information Commands

These commands provide information about your system.

uname - System Information

The uname command displays system information.

Syntax: `bash uname [OPTION] `

Options: | Option | Description | |--------|-------------| | -a | All information | | -s | Kernel name | | -r | Kernel release | | -m | Machine hardware | | -o | Operating system |

Examples: `bash uname

Output: Linux

uname -a

Output: Linux hostname 5.4.0-42-generic x86_64 GNU/Linux

uname -r

Output: 5.4.0-42-generic

`

df - Disk Space Usage

The df command displays filesystem disk space usage.

Syntax: `bash df [OPTION] [FILE] `

Options: | Option | Description | |--------|-------------| | -h | Human-readable format | | -T | Show filesystem type | | -i | Show inode information |

Examples: `bash df

Show disk usage for all mounted filesystems

df -h

Show disk usage in human-readable format

df -h /home

Show disk usage for specific directory

df -T

Show filesystem types

`

du - Directory Space Usage

The du command displays directory space usage.

Syntax: `bash du [OPTION] [DIRECTORY] `

Options: | Option | Description | |--------|-------------| | -h | Human-readable format | | -s | Summary only | | -a | All files | | --max-depth=N | Limit depth |

Examples: `bash du -h

Show directory sizes in current directory

du -sh *

Show summary of all items in current directory

du -h --max-depth=1

Show directory sizes one level deep

du -ah | sort -rh | head -10

Show top 10 largest files/directories

`

free - Memory Usage

The free command displays memory usage information.

Syntax: `bash free [OPTION] `

Options: | Option | Description | |--------|-------------| | -h | Human-readable format | | -m | Show in megabytes | | -g | Show in gigabytes |

Examples: `bash free

Show memory usage in bytes

free -h

Show memory usage in human-readable format

free -m

Show memory usage in megabytes

`

Text Processing Commands

These commands help you process and manipulate text files.

sort - Sort Lines

The sort command sorts lines in text files.

Syntax: `bash sort [OPTION] FILE `

Options: | Option | Description | |--------|-------------| | -r | Reverse order | | -n | Numeric sort | | -k | Sort by column | | -u | Remove duplicates |

Examples: `bash sort file.txt

Sort lines alphabetically

sort -r file.txt

Sort in reverse order

sort -n numbers.txt

Sort numerically

sort -k 2 data.txt

Sort by second column

sort -u file.txt

Sort and remove duplicates

`

uniq - Remove Duplicate Lines

The uniq command removes duplicate adjacent lines.

Syntax: `bash uniq [OPTION] FILE `

Options: | Option | Description | |--------|-------------| | -c | Count occurrences | | -d | Show only duplicates | | -u | Show only unique lines |

Examples: `bash sort file.txt | uniq

Remove duplicates (sort first)

uniq -c file.txt

Count occurrences of each line

uniq -d file.txt

Show only duplicate lines

`

wc - Word Count

The wc command counts lines, words, and characters.

Syntax: `bash wc [OPTION] FILE `

Options: | Option | Description | |--------|-------------| | -l | Count lines | | -w | Count words | | -c | Count characters | | -m | Count characters (multibyte) |

Examples: `bash wc file.txt

Output: lines words characters filename

wc -l file.txt

Count only lines

wc -w *.txt

Count words in all .txt files

ls | wc -l

Count files in directory

`

Network Commands

These commands help you work with network connections and troubleshooting.

ping - Test Network Connectivity

The ping command tests network connectivity to a host.

Syntax: `bash ping [OPTION] HOST `

Options: | Option | Description | |--------|-------------| | -c COUNT | Send COUNT packets | | -i INTERVAL | Wait INTERVAL seconds | | -s SIZE | Packet size |

Examples: `bash ping google.com

Ping google.com continuously

ping -c 4 google.com

Send 4 ping packets

ping -c 10 -i 2 192.168.1.1

Ping 10 times with 2-second intervals

`

wget - Download Files

The wget command downloads files from web servers.

Syntax: `bash wget [OPTION] URL `

Options: | Option | Description | |--------|-------------| | -O | Output filename | | -c | Continue partial download | | -r | Recursive download | | -q | Quiet mode |

Examples: `bash wget https://example.com/file.zip

Download file

wget -O myfile.zip https://example.com/file.zip

Download with specific filename

wget -c https://example.com/largefile.iso

Continue interrupted download

wget -r -np https://example.com/directory/

Recursively download directory

`

curl - Transfer Data

The curl command transfers data to/from servers.

Syntax: `bash curl [OPTION] URL `

Options: | Option | Description | |--------|-------------| | -o | Output to file | | -O | Use remote filename | | -L | Follow redirects | | -H | Add header |

Examples: `bash curl https://api.example.com/data

GET request to API

curl -o file.html https://example.com

Download and save to file

curl -H "Authorization: Bearer token" https://api.example.com

Request with custom header

curl -X POST -d "data=value" https://api.example.com

POST request with data

`

Archive and Compression

These commands help you create and extract archive files.

tar - Archive Files

The tar command creates and extracts archive files.

Syntax: `bash tar [OPTION] ARCHIVE_NAME FILES `

Common Options: | Option | Description | |--------|-------------| | -c | Create archive | | -x | Extract archive | | -v | Verbose output | | -f | Specify filename | | -z | Use gzip compression | | -j | Use bzip2 compression |

Examples: `bash tar -cvf archive.tar files/

Create tar archive

tar -czvf archive.tar.gz files/

Create compressed tar archive

tar -xvf archive.tar

Extract tar archive

tar -xzvf archive.tar.gz

Extract compressed tar archive

tar -tvf archive.tar

List contents without extracting

`

gzip/gunzip - Compress Files

The gzip command compresses files, and gunzip decompresses them.

Examples: `bash gzip file.txt

Compresses file.txt to file.txt.gz

gunzip file.txt.gz

Decompresses file.txt.gz to file.txt

gzip -r directory/

Recursively compress files in directory

gzip -d file.txt.gz

Decompress (same as gunzip)

`

Command Line Tips and Tricks

Command History

Linux keeps a history of commands you have executed.

History Commands: `bash history

Show command history

history | grep "search_term"

Search command history

!!

Repeat last command

!n

Execute command number n from history

!string

Execute last command starting with string

ctrl+r

Reverse search through history

`

Command Chaining

You can chain commands using various operators.

Operators: | Operator | Description | |----------|-------------| | ; | Execute commands sequentially | | && | Execute second command only if first succeeds | | \|\| | Execute second command only if first fails | | \| | Pipe output of first command to second |

Examples: `bash command1; command2

Execute both commands

command1 && command2

Execute command2 only if command1 succeeds

command1 || command2

Execute command2 only if command1 fails

ls | grep ".txt"

List files and filter for .txt files

ps aux | grep apache | wc -l

Count apache processes

`

Input/Output Redirection

Redirect command input and output to files.

Redirection Operators: | Operator | Description | |----------|-------------| | > | Redirect output (overwrite) | | >> | Redirect output (append) | | < | Redirect input | | 2> | Redirect error output | | &> | Redirect both output and errors |

Examples: `bash command > output.txt

Redirect output to file (overwrite)

command >> output.txt

Redirect output to file (append)

command < input.txt

Use file as input

command 2> error.log

Redirect errors to file

command &> all_output.txt

Redirect both output and errors

command > /dev/null 2>&1

Discard all output

`

Wildcards and Globbing

Use wildcards to match multiple files.

Wildcards: | Wildcard | Description | |----------|-------------| | * | Matches any characters | | ? | Matches single character | | [abc] | Matches any of a, b, or c | | [a-z] | Matches any lowercase letter | | {a,b,c} | Matches a, b, or c |

Examples: `bash ls *.txt

List all .txt files

rm file?.log

Remove files like file1.log, file2.log

cp [abc]*.txt backup/

Copy files starting with a, b, or c

mv {file1,file2,file3}.txt archive/

Move specific files

`

Environment Variables

Environment variables store system and user information.

Common Variables: | Variable | Description | |----------|-------------| | HOME | User's home directory | | PATH | Executable search path | | USER | Current username | | PWD | Current working directory | | SHELL | Current shell |

Examples: `bash echo $HOME

Display home directory

echo $PATH

Display executable search paths

export MY_VAR="value"

Set environment variable

env

Display all environment variables

which command

Show path to command executable

`

Aliases

Create shortcuts for frequently used commands.

Examples: `bash alias ll='ls -la'

Create alias for detailed listing

alias grep='grep --color=auto'

Add color to grep output

alias ..='cd ..'

Shortcut to go up one directory

unalias ll

Remove alias

alias

List all aliases

`

This comprehensive guide covers the essential Linux shell commands that form the foundation of command-line proficiency. Regular practice with these commands will significantly improve your efficiency when working with Linux systems. Remember that most commands have additional options and features that can be explored using the man command (e.g., man ls to view the manual page for the ls command).

The key to mastering Linux commands is consistent practice and experimentation in a safe environment. Start with basic commands and gradually incorporate more advanced features as you become comfortable with the fundamentals.

Tags

  • Command Line
  • Linux
  • bash
  • shell
  • terminal

Related Articles

Popular Technical Articles & Tutorials

Explore our comprehensive collection of technical articles, programming tutorials, and IT guides written by industry experts:

Browse all 8+ technical articles | Read our IT blog

Linux Shell Commands: Complete Guide for Beginners &amp; Pros