Unit

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 --help or --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 projects

The 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.
  • history displays saved command history in many shells.
  • Press Ctrl+C to 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 archive

man 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 -
  • pwd prints the current working directory.
  • ls lists directory contents. -l gives a detailed listing, -a includes hidden entries, and -h uses human-readable sizes with a detailed listing.
  • cd changes the working directory. With no argument, it normally changes to the home directory.
NotationMeaningExample use
.Current directoryls .
..Parent directorycd ..
~Current user's home directorycd ~/Documents
/Root directory, or a path separatorls /
-Previous directory for commands such as cdcd -
*Wildcard matching zero or more charactersls *.log
?Wildcard matching one characterls file?.txt
Quoted pathPreserves spaces and prevents the shell from interpreting many special characterscd '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-directory

touch 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.log
  • cat prints short files in full. Avoid using it for huge files.
  • less displays content one page at a time. Press q to quit.
  • head shows the beginning and tail shows the end. Use -n to select a number of lines.
  • tail -f follows a growing file, which is useful for logs. Press Ctrl+C to stop following.
  • wc counts lines, words, and bytes; wc -l counts lines.
  • file reports 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.

PermissionSymbolNumeric valueMeaning
Readr4Read file contents; list directory names when applied to a directory
Writew2Change file contents; create or remove directory entries when applied to a directory
Executex1Run a program; access items within a directory
Owner, group, otheru, g, oThree permission groupsRules 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.txt

Numeric 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.txt

sudo 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.

OperatorEffectExampleCommon caution
>Write standard output, replacing the filels > listing.txtExisting contents are overwritten
>>Append standard outputdate >> activity.logRepeated commands grow the file
<Read standard input from a filesort < names.txtInput must be in the expected format
|Pipe output into another commandps aux | lessThe second command receives output, not the original file
2>Redirect standard errorfind / -name '*.log' 2> errors.txtErrors are no longer shown on the terminal
2>&1Send standard error to the current standard-output destinationcommand > all.txt 2>&1Order matters
teeDisplay output and write a copyls -lah | tee directory-listing.txtUse 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.txt

Archives 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.zip
  • tar -c creates, -x extracts, -t lists contents, -z uses gzip, and -f names the archive file.
  • Inspect an archive with tar -tzf or unzip -l before 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
clear

A 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

CommandPrimary purposeCommon optionsExampleSafety note
pwdPrint current directoryNonepwdRead-only
lsList items-l -a -hls -lahCheck hidden items and exact names
cdChange directory-cd ~/DocumentsConfirm location after changing
mkdirCreate directories-pmkdir -p project/docsCreates the requested path
touchCreate or timestamp a fileNonetouch notes.txtMay change an existing timestamp
cpCopy items-r -icp -r project project-copyDestination files may be overwritten
mvMove or rename-imv old.txt new.txtCan replace a destination
rmDelete files-i -r -frm -i file.txtUsually no recycle bin; recursive deletion is dangerous
catPrint short filesNonecat notes.txtLarge output can overwhelm the terminal
lessView content page by pageNoneless application.logRead-only viewer
headShow beginning of a file-nhead -n 20 fileRead-only
tailShow end or follow a file-n -ftail -f application.logStop a live follow with Ctrl+C
findLocate files and directories-name -type -mtimefind . -type f -name '*.txt'Some actions can modify or delete results
grepSearch text-R -n -i -vgrep -Rni 'error' .Quote patterns and limit the search scope
chmodChange permissionsSymbolic or numeric modeschmod u+x script.shExcessive permissions expose data
tarCreate, inspect, or extract archives-c -x -t -z -ftar -tzf project.tar.gzInspect contents before extraction
psList processesauxps auxRead-only
killSignal a processSignal options varykill 1234Verify the PID before signaling
dfShow file-system space-hdf -hRead-only
duMeasure file or directory usage-s -hdu -sh projectLarge trees may take time
curlRetrieve or test URLs-I -ocurl -I https://example.comDo not execute downloaded content blindly
sshOpen a remote shell-p -issh user@example.comVerify the host and protect credentials

Command safety and recovery

  1. Run pwd before file operations when there is any doubt about your location.
  2. Preview targets with ls or a non-destructive find command before using rm, recursive options, or wildcards.
  3. Quote paths such as 'Annual Reports/report.txt' when they contain spaces or shell-special characters.
  4. Use rm -i for interactive confirmation and avoid combining -r and -f unless the exact target has been verified.
  5. Use Ctrl+C to 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 project

For 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.