Useful Terminal Commands
Learn essential Unix-like terminal commands for files, directories, searching, permissions, processes, archives, networking, and safe command-line work.
A terminal is a text-based interface used to run commands. A shell, such as Bash or Zsh, is the program that interprets what you type and starts commands. Linux and macOS both provide Unix-like terminals, although individual options and installed programs can differ.
The prompt is the text that indicates the shell is ready for input. It commonly includes your username, computer name, and current directory. The working directory is the directory in which a command operates by default.
Terminal fundamentals
How commands are structured
A command is a program or shell instruction invoked from the prompt. Its usual structure is:
command [options] [arguments]- An argument is a value supplied to a command, often a file name or path.
- An option modifies behavior and commonly begins with
-or--. - A short option is often written as
-l; several short options may sometimes be combined, as in-lah. - A long option is often written as
--helpor--human-readable. - A flag is an option that turns a behavior on or off, usually without a separate value.
- A path identifies a file or directory.
For example, in ls -lah Documents, ls is the command, -lah contains options, and Documents is an argument.
Absolute and relative paths
An absolute path is a complete location beginning at the root directory, written as / on Unix-like systems. A relative path is interpreted from the current working directory.
pwd
ls /var/log
ls ../Downloads
cd /home/alex/projects
cd projectsThe last command works only when a directory named projects exists below the current directory. A home directory is a user's personal default directory and is represented by ~. Unix-like systems are generally case-sensitive: Report.txt, report.txt, and REPORT.TXT can be different names.
Completion and history
- Press Tab to complete a command, file name, directory, or path. It also reduces spelling and case errors.
- Use the Up and Down arrow keys to move through previously entered commands.
historydisplays saved command history in many shells.- Press
Ctrl+Cto interrupt a running command or cancel the current input.
Getting help
Read documentation before using an unfamiliar option, especially when a command can overwrite or delete data.
man ls
man chmod
ls --help
apropos archive
man -k archiveman opens a manual page, usually in a pager such as less. Search inside a manual page with /word, then press n for the next match. Many programs support --help, but this is not universal. apropos and man -k search manual-page descriptions by keyword.
Usage notation describes the expected structure. Text in square brackets is usually optional, angle-bracket text represents a value to replace, and a vertical bar means a choice. For example, cp [option] source destination means that options may be supplied before the source and destination. Read option descriptions for effects, required values, and defaults.
Navigating the file system
pwd
ls
ls -l
ls -a
ls -h
ls -lah
cd /var/log
cd ..
cd ~
cd -pwdprints the current working directory.lslists directory contents.-lgives a detailed listing,-aincludes hidden entries, and-huses human-readable sizes with a detailed listing.cdchanges the working directory. With no argument, it normally changes to the home directory.
| Notation | Meaning | Example use |
|---|---|---|
. | Current directory | ls . |
.. | Parent directory | cd .. |
~ | Current user's home directory | cd ~/Documents |
/ | Root directory, or a path separator | ls / |
- | Previous directory for commands such as cd | cd - |
* | Wildcard matching zero or more characters | ls *.log |
? | Wildcard matching one character | ls file?.txt |
| Quoted path | Preserves spaces and prevents the shell from interpreting many special characters | cd 'Project Files' |
Creating, copying, moving, and deleting
touch notes.txt
mkdir project
mkdir -p project/docs
cp notes.txt notes-backup.txt
cp -r project project-copy
mv notes-backup.txt archive.txt
mv archive.txt project/
rm -i archive.txt
rmdir empty-directorytouch creates an empty file if it does not exist or updates its timestamps if it does. mkdir creates a directory; mkdir -p also creates missing parent directories. cp copies files, while cp -r copies a directory and its contents. mv moves or renames an item. rmdir removes empty directories.
rm removes files. Recursive deletion, such as rm -r, can remove a directory tree, and -f suppresses many confirmations and errors. These options are dangerous together. Unix-like terminal deletion commonly does not use a recycle bin.
Viewing and inspecting file contents
cat notes.txt
less application.log
head -n 20 application.log
tail -n 20 application.log
tail -f application.log
wc application.log
wc -l application.log
file application.logcatprints short files in full. Avoid using it for huge files.lessdisplays content one page at a time. Pressqto quit.headshows the beginning andtailshows the end. Use-nto select a number of lines.tail -ffollows a growing file, which is useful for logs. PressCtrl+Cto stop following.wccounts lines, words, and bytes;wc -lcounts lines.filereports a likely file type based on its contents, not merely its extension.
For example, a log can be read and monitored with less application.log and then tail -f application.log.
Searching for files and text
Finding files
find . -type f -name '*.txt'
find /var/log -type f -name '*.log' -mtime -1
find . -type d -name 'backup*'
find . -path './build/*'find locates items below a starting path. Common tests include -name for a name pattern, -type f for regular files, -type d for directories, -path for a path pattern, and -mtime -1 for files modified within roughly the last day. Quote patterns so the shell does not expand them before find receives them.
Searching file contents
grep 'error' application.log
grep -n 'error' application.log
grep -i 'error' application.log
grep -Rni 'error' .
grep -v 'debug' application.log
find . -type f -name '*.log' -exec grep -n 'error' {} +grep searches text for a pattern. -n shows line numbers, -i ignores case, -R searches recursively, and -v shows lines that do not match. The final example limits the search to files found by find, rather than recursively searching every item indiscriminately.
A wildcard is a shell pattern, not the same thing as a full regular expression. Use quotes for literal search text and paths containing spaces, dollar signs, parentheses, or wildcard characters. Single quotes usually prevent the shell from expanding variables and patterns.
Permissions and ownership
A detailed listing such as ls -l may begin with a string like -rwxr-x---. The first character identifies the item type; the next nine positions are permissions for the owner, group, and other users.
| Permission | Symbol | Numeric value | Meaning |
|---|---|---|---|
| Read | r | 4 | Read file contents; list directory names when applied to a directory |
| Write | w | 2 | Change file contents; create or remove directory entries when applied to a directory |
| Execute | x | 1 | Run a program; access items within a directory |
| Owner, group, other | u, g, o | Three permission groups | Rules are evaluated for the file owner, group members, and everyone else |
chmod changes permissions. Symbolic mode names the category and action:
chmod u+x script.sh
chmod g-w shared.txt
chmod o-r private.txtNumeric mode adds values for each category. For example, chmod 750 script.sh gives the owner read, write, and execute permissions; the group read and execute permissions; and others no permissions. chown changes an owner, and chgrp changes a group where the operating system and account permissions allow it.
chown user file.txt
chown user:group file.txt
chgrp developers file.txtsudo runs an authorized command with elevated privileges. Elevation may be needed to modify protected system files, but it does not make an unsafe command safe. Verify the command and target first, and use the smallest necessary scope.
Redirecting and combining output
Commands normally use three streams: standard input for incoming data, standard output for normal results, and standard error for error messages. Redirection sends a stream to or from a file. A pipe sends one command's standard output to another command's standard input.
| Operator | Effect | Example | Common caution |
|---|---|---|---|
> | Write standard output, replacing the file | ls > listing.txt | Existing contents are overwritten |
>> | Append standard output | date >> activity.log | Repeated commands grow the file |
< | Read standard input from a file | sort < names.txt | Input must be in the expected format |
| | Pipe output into another command | ps aux | less | The second command receives output, not the original file |
2> | Redirect standard error | find / -name '*.log' 2> errors.txt | Errors are no longer shown on the terminal |
2>&1 | Send standard error to the current standard-output destination | command > all.txt 2>&1 | Order matters |
tee | Display output and write a copy | ls -lah | tee directory-listing.txt | Use tee -a to append instead of replace |
command > output.txt
command >> output.txt
command < input.txt
command1 | command2
command > all.txt 2>&1
ls -lah | tee directory-listing.txtArchives and compression
An archive bundles files into one file. Compression reduces its size. A .tar file is an archive and is not necessarily compressed; .tar.gz or .tgz is a tar archive compressed with gzip. .zip combines archiving and compression in a different format.
tar -czf project.tar.gz project
tar -tzf project.tar.gz
tar -xzf project.tar.gz
gzip report.txt
gunzip report.txt.gz
zip -r project.zip project
unzip -l project.zip
unzip project.ziptar -ccreates,-xextracts,-tlists contents,-zuses gzip, and-fnames the archive file.- Inspect an archive with
tar -tzforunzip -lbefore extraction, especially if its source is untrusted. - Check the destination and archive paths before extracting because an archive may contain unexpected names or overwrite existing files.
Processes and system information
ps aux
top
kill 1234
whoami
hostname
uname -a
date
df -h
du -sh project
clearA process is a running instance of a program. Each process has a PID, or process identifier. ps aux displays a broad process listing. top provides an interactive view; some systems provide an equivalent such as htop if installed. kill PID sends the default termination signal and should be preferred over forceful signals when possible.
whoami shows the effective username, hostname shows the system name, uname reports system information, and date prints the current date and time. df -h reports free space on mounted file systems, while du -sh path reports the total usage of a file or directory. clear clears the visible terminal screen without deleting files.
Networking and remote access
ping example.com
curl https://example.com
curl -I https://example.com
ssh user@example.com
scp report.txt user@example.com:~/
rsync -av project/ user@example.com:~/project/ping performs a basic reachability test, although firewalls may block its packets. curl retrieves URLs and can test HTTP endpoints; -I requests response headers when supported. ssh opens a secure remote shell. scp copies files over SSH, while rsync can efficiently synchronize directory contents.
Core terminal command reference
| Command | Primary purpose | Common options | Example | Safety note |
|---|---|---|---|---|
pwd | Print current directory | None | pwd | Read-only |
ls | List items | -l -a -h | ls -lah | Check hidden items and exact names |
cd | Change directory | - | cd ~/Documents | Confirm location after changing |
mkdir | Create directories | -p | mkdir -p project/docs | Creates the requested path |
touch | Create or timestamp a file | None | touch notes.txt | May change an existing timestamp |
cp | Copy items | -r -i | cp -r project project-copy | Destination files may be overwritten |
mv | Move or rename | -i | mv old.txt new.txt | Can replace a destination |
rm | Delete files | -i -r -f | rm -i file.txt | Usually no recycle bin; recursive deletion is dangerous |
cat | Print short files | None | cat notes.txt | Large output can overwhelm the terminal |
less | View content page by page | None | less application.log | Read-only viewer |
head | Show beginning of a file | -n | head -n 20 file | Read-only |
tail | Show end or follow a file | -n -f | tail -f application.log | Stop a live follow with Ctrl+C |
find | Locate files and directories | -name -type -mtime | find . -type f -name '*.txt' | Some actions can modify or delete results |
grep | Search text | -R -n -i -v | grep -Rni 'error' . | Quote patterns and limit the search scope |
chmod | Change permissions | Symbolic or numeric modes | chmod u+x script.sh | Excessive permissions expose data |
tar | Create, inspect, or extract archives | -c -x -t -z -f | tar -tzf project.tar.gz | Inspect contents before extraction |
ps | List processes | aux | ps aux | Read-only |
kill | Signal a process | Signal options vary | kill 1234 | Verify the PID before signaling |
df | Show file-system space | -h | df -h | Read-only |
du | Measure file or directory usage | -s -h | du -sh project | Large trees may take time |
curl | Retrieve or test URLs | -I -o | curl -I https://example.com | Do not execute downloaded content blindly |
ssh | Open a remote shell | -p -i | ssh user@example.com | Verify the host and protect credentials |
Command safety and recovery
- Run
pwdbefore file operations when there is any doubt about your location. - Preview targets with
lsor a non-destructivefindcommand before usingrm, recursive options, or wildcards. - Quote paths such as
'Annual Reports/report.txt'when they contain spaces or shell-special characters. - Use
rm -ifor interactive confirmation and avoid combining-rand-funless the exact target has been verified. - Use
Ctrl+Cto interrupt a command that is running too long, producing unwanted output, or following a live log.
Troubleshooting common errors
No such file or directory
Check for an incorrect path, a misspelled name, a case mismatch, or an unexpected working directory. Run pwd, inspect with ls -lah, use Tab completion, or locate the item with find.
Permission denied
Inspect the permissions with ls -l. A script may lack execute permission, or a protected location may require authorization. Use chmod only when the change is appropriate, and use sudo only when authorized and necessary.
Command not found
Check spelling and run command -v command-name. The program may not be installed or its executable may not be in PATH. Consult the package-management documentation for the operating system rather than copying an untrusted installation command.
A command hangs or prints too much
The process may still be working, waiting for input, or producing extensive output. Wait briefly, press Ctrl+C to interrupt, pipe output into less, or narrow the path and search pattern.
Deletion behaves unexpectedly
If rm refuses a directory, the target may require a deliberate recursive operation. First run pwd and preview the exact target with ls. A wildcard may also have expanded to more names than expected. Use rm -i and verify each result.
Quoted names or patterns behave unexpectedly
The shell may have interpreted spaces, wildcards, variables, or other special characters. Quote literal search patterns with single quotes where appropriate, quote paths containing spaces, and test patterns in a small known directory.
Practice workflow
The following sequence creates a small project, examines it, searches it, archives it, and checks its storage use:
mkdir -p project/docs
cd project
touch notes.txt
cp notes.txt notes-backup.txt
mv notes-backup.txt archive.txt
ls -lah
grep -Rni 'error' .
cd ..
tar -czf project.tar.gz project
tar -tzf project.tar.gz
df -h
du -sh projectFor remote work, connect and transfer a file only after confirming the account, host, destination, and authentication method:
ssh user@example.com
scp report.txt user@example.com:~/These commands form a foundation for shell scripting, text processing, Git workflows, package management, and remote administration. Consult each command's manual page before relying on platform-specific options.
For further study, see Essential Linux Commands, Less Text Viewer, Modify File Permissions, Check Disk Space, and Enable SSH in Raspbian.