Skip to content
DBDeependra Bhatta~/notes
Linux#networking · #bash · #cheat-sheet · #systemd · #linux

Essential Linux Commands for DevOps

A task-based Linux command reference: navigating and managing files, reading logs, grep, sed, cut and awk, redirection, Vim, services, and basic networking.

· updated · 16 min read
ON THIS PAGE

Most server work over SSH comes down to a few dozen commands: moving through the file system, reading logs, searching and editing text, and controlling services. This reference groups those commands by task, with the flags that matter and a short example for each. Users, permissions, packages, archives and processes are covered in the next part, so each command is explained only once.

Getting help

CommandWhat it does
TabCompletes a command, file or directory name
Tab TabShows all possible completions
man lsOpens the manual page for a command (press q to quit)
ls --helpPrints a short list of options
info lsOpens the longer GNU info page
apropos copySearches manual page descriptions; useful when you forget a command's name
CommandWhat it does
pwdPrints the current directory
cd /optGoes to an absolute path
cd ..Goes up one level
cd ../..Goes up two levels
cd -Goes back to the previous directory
cd ~ or cdGoes to your home directory

Listing with ls

CommandWhat it does
lsLists the contents of the current directory
ls -aIncludes hidden files (names that start with .)
ls -lLong list: permissions, owner, size, date
ls -alLong list including hidden files
ls -lhLong list with human-readable sizes (4.0K, 1.2G)
ls -lrLong list in reverse order
ls -ltLong list sorted by modification time, newest first
ls -ltuLong list sorted by last access time
ls -iShows inode numbers (what an inode is)
tree / tree -aShows a directory tree, -a includes hidden files (install with sudo apt install tree)

The first character of each ls -l line is the file type (- file, d directory, l link). All seven types are listed in Introduction to Linux.

Creating, copying, moving and deleting

terminal
$ touch notes.txt
$ mkdir project
$ mkdir -p devops/scripts/yaml
$ mkdir dir{1..5}

mkdir -p creates missing parent directories. dir{1..5} is brace expansion: the shell turns it into dir1 dir2 dir3 dir4 dir5.

CommandWhat it does
cp report.txt backup/Copies a file
cp -i a.txt b.txtAsks before overwriting
cp -r dir1/ dir2/Copies a directory and everything inside it
mv old.txt new.txtRenames a file
mv file.txt /home/user/docs/Moves a file
mv dir1 dir2Moves dir1 into dir2 (or renames it if dir2 does not exist)
mv -i a.txt b.txtAsks before overwriting
rm file.txtDeletes a file
rm -i file.txtAsks before deleting
rm -r dirDeletes a directory and its contents
rm -rf dirSame, without any prompts
rmdir dir or rm -d dirDeletes a directory only if it is empty

mv does not need -r; it moves directories with their contents by default.

To inspect a file:

CommandWhat it does
file nameShows the file type (text, binary, directory)
stat nameShows size, permissions, owner, inode and timestamps

Reading files and logs

CommandWhat it does
cat filePrints the whole file
cat -n filePrints with line numbers
cat file1 file2Prints several files one after another
tac filePrints the file with the last line first
head fileFirst 10 lines
head -n 20 fileFirst 20 lines
tail fileLast 10 lines
tail -n 20 fileLast 20 lines
tail -f fileFollows the file and prints new lines as they arrive
wc fileCounts lines, words and bytes
uniq fileRemoves repeated lines that are next to each other (use sort file | uniq for all duplicates)

For long files, use a pager:

  • more file: Enter moves one line, Space moves one page.
  • less file (more capable): Space next page, b previous page, d half a page down, /text searches forward, n next match, q quits.

The most useful logs for troubleshooting live in /var/log:

Log fileWhat it contains
/var/log/syslogGeneral system and service messages
/var/log/dpkg.logPackage installs and removals
/var/log/cloud-init-output.logOutput of user data scripts that run when a cloud VM first boots
terminal
$ tail -f /var/log/syslog
$ wc -l /var/log/syslog

Finding files

find

find walks the directory tree and checks each file against your tests.

terminal
$ sudo find / -name dpkg.log
$ find . -name "*.log"
$ find / -type d -name Pictures
$ find . -type d -name "*terraform*"
$ sudo find / -type l -ls
$ sudo find /etc/ -group shadow -ls
OptionSearches by
-nameFile name (quote patterns with *)
-typeType: f file, d directory, l link
-user / -groupOwner or group
-inumInode number
-lsPrints details for each match

The starting point matters: / searches the whole system (an absolute path), . searches from the current directory (a relative path).

locate

locate is faster than find because it searches a prebuilt database instead of the disk. Refresh the database with updatedb to include new files.

terminal
$ sudo apt install plocate
$ sudo updatedb
$ locate dpkg.log
$ locate -i readme.md

Older releases use the mlocate package; newer Debian and Ubuntu releases ship plocate. -i ignores case.

which

which shows the full path of a command:

terminal
$ which apt

Searching and editing text

grep

grep prints the lines of a file that match a pattern.

CommandWhat it does
grep name test.txtLines containing name (case-sensitive)
grep -E "cat|dog" test.txtEnables Extended Regular Expressions (ERE) for advanced patterns (e.g., alternation with |)
grep -i name test.txtSame, ignoring case
grep -n name test.txtAdds line numbers
grep -v hello test.txtLines that do not contain hello
grep -r error /var/log/Searches all files under a directory
grep "^name" test.txtLines that start with name
grep "name$" test.txtLines that end with name
grep "[nN]ame" test.txtMatches name or Name
grep "[0-9][0-9]$" test.txtLines that end with two digits

^, $ and [...] are regular expression symbols. Quote the pattern so the shell does not change it.

sed

sed (stream editor) processes text line by line. It prints selected lines of a file and performs find-and-replace, which makes it a standard tool in scripts.

terminal
$ sed -n '3p' /etc/passwd
$ sed -n '$p' /etc/passwd
$ sed -n '3,6!p' /etc/passwd
$ sed -e 's/ansible/devops/g' /etc/passwd
$ sed -e 's/ansible/devops/g' word.txt > newtmp.txt
$ sed -i 's/Suryaraj/raj/g' abc.txt
  • -n stops sed from printing every line; p prints only the lines you select. 3p is line 3, $p is the last line, 3,6!p is everything except lines 3 to 6.
  • In s/find/replace/g, s means substitute and g replaces every match on the line, not only the first.
  • -e gives an expression; the result goes to the screen and the file is unchanged.
  • -i edits the file in place.

In my WordPress lab, sed set the database name in the WordPress config file, running as the www-data user:

terminal
$ sudo -u www-data sed -i 's/database_name_here/wordpress/' /srv/www/wordpress/wp-config.php

cut

cut extracts characters or fields (columns) from each line. A delimiter is the character that separates fields, such as : in /etc/passwd.

CommandWhat it does
cut -c1 /etc/passwdFirst character of each line
cut -c1-5 /etc/passwdCharacters 1 to 5
cut -d ':' -f1 /etc/passwdFirst field, using : as the delimiter (the usernames)
cut -d ':' -f2-3 /etc/passwdFields 2 to 3
cut -d ' ' -f1 fileFirst field, using a space as the delimiter

awk

awk is a small language for processing text, mostly used to print columns and build quick reports. The syntax is awk '/pattern/ {action}' file.

awk splits each line on whitespace and stores the fields in $1, $2, $3 and so on; $0 is the whole line. -F sets a different field separator. Use single quotes so the shell does not expand $1.

terminal
$ awk -F ':' '{print $1}' /etc/passwd
$ df -h | awk '{print $2}'
$ awk '/error/ {print $0}' /var/log/syslog

Redirection and pipes

Every command has three streams:

StreamNumberExample
Standard input (stdin)0wc with no file waits for you to type; press Ctrl+D to finish
Standard output (stdout)1The normal output of ls, whoami, date
Standard error (stderr)2Messages like command not found, No such file or directory, Permission denied
OperatorWhat it does
> or 1>Sends stdout to a file and overwrites it
>>Sends stdout to a file and appends to it
2> / 2>>Sends stderr to a file (overwrite / append)
&>Sends both stdout and stderr to a file
> /dev/nullThrows the output away (/dev/null discards everything written to it)
<Reads stdin from a file
<< EOFHere document: reads stdin from the lines that follow, up to EOF
|Pipe: sends stdout of one command to stdin of the next
terminal
$ who > users.txt
$ date >> command.out
$ whoami >> command.out
$ lss 2> error.out
$ ls /binn 2>> error.out
$ wc -l << EOF
This is a simple program
EOF

tee writes its input to a file and to the screen. tee overwrites the file and tee -a appends. Combined with a here document, tee -a adds several lines to a file in one command:

terminal
$ tee -a filename << EOF
We are adding some content
to the file filename.
EOF

sudo tee applies the same pattern to files owned by root. sudo echo ... >> file fails there, because the shell performs the redirection as your own user.

Editing files with Vim

Vim (Vi Improved), or at least vi, is present on almost every server, which makes it the editor you can always rely on over SSH. Install it with sudo apt install vim (Debian, Ubuntu) or sudo dnf install vim (RHEL, Fedora).

Vim has three main modes:

ModeHow to enter itUsed for
Normal modeEscMoving around and editing with keys
Insert modei (before cursor), a (after cursor)Typing text
Command-line mode: from normal modeSaving, quitting, search and replace

Moving around (normal mode)

KeysAction
h j k lLeft, down, up, right
w / b / eNext word / previous word / end of word (3w jumps three words)
0 / $Start / end of the line
gg / G / 2GFirst line / last line / line 2
f x / F xNext / previous occurrence of character x on the line
* / #Next / previous occurrence of the word under the cursor
/text then n / NSearch forward, then next / previous match

Editing (normal mode)

KeysAction
o / ONew line below / above and enter insert mode
x / XDelete the character under / before the cursor
rReplace the character under the cursor
dw / d2eDelete a word / delete to the end of the second word
dd / 3ddDelete a line / three lines
yy / 3yyCopy a line / three lines
p / PPaste below / above
u / U / Ctrl+rUndo / undo all changes on the line / redo
vVisual mode: select text with movement keys, then d to delete or y to copy

Saving and quitting (command-line mode)

CommandAction
:wSave
:qQuit
:wq or :xSave and quit
:q!Quit without saving
:w! / :wq!Force save / force save and quit
:20Go to line 20
:set nu / :set nonuShow / hide line numbers
:%s/old/new/Replace the first old on every line
:%s/old/new/gReplace every old in the file
:helpOpen Vim help

vim +7 test.txt opens the file with the cursor on line 7.

System information

CommandWhat it does
dateCurrent date and time
timedatectlTime, time zone and NTP sync status
sudo timedatectl set-timezone Asia/KathmanduChanges the time zone
sudo timedatectl set-ntp trueTurns on NTP time sync (fixes clock drift)
hostnameShows the host name
sudo hostnamectl set-hostname jenkinsChanges the host name
whoamiShows the current username
df -hDisk usage per file system, human-readable
df -hiInode usage per file system
du -sh *Size of each item in the current directory
free -mMemory usage in MB
echo $SHELLYour login shell
echo $?Exit code of the last command: 0 means success, anything else means failure
clearClears the screen
passwdChanges your password

history lists the commands you ran before. !136 runs command number 136 again and !! repeats the last command (sudo !! reruns the last command with sudo).

Networking and downloads

CommandWhat it does
ip addr showAll network interfaces and their IP addresses
ip -4 addr showOnly IPv4 addresses
ifconfigOlder tool with similar output; needs the net-tools package
wget URLDownloads a file into the current directory
curl URLPrints the response to the screen
curl -o file.zip URLSaves the response as file.zip
curl -O URLSaves the response with the remote file name
curl -k URLSkips TLS certificate checks (only for testing self-signed certificates)
curl localhostQuick check that a local web server answers

Managing services with systemctl

systemctl controls services (background programs) on systems that use systemd, which includes current Ubuntu, Debian and RHEL.

CommandWhat it does
sudo systemctl start apache2Starts a service now
sudo systemctl stop apache2Stops it
sudo systemctl restart apache2Stops and starts it
sudo systemctl reload apache2Re-reads the config without a full restart (if the service supports it)
sudo systemctl enable apache2Starts it automatically at boot
sudo systemctl disable apache2Stops starting it at boot
systemctl status apache2Shows state and recent log lines
systemctl is-active apache2Prints active or inactive

The older service command still works and calls systemd underneath: sudo service apache2 status (also start, stop, restart, reload). To write your own service, see Running Tomcat as a systemd Service.

Key takeaways

  • man, --help and apropos answer most "how do I" questions without leaving the terminal.
  • tail -f, grep, less and /var/log are the core of log debugging.
  • > overwrites and >> appends; send errors with 2> and discard output with /dev/null.
  • Test sed without -i before editing a file in place, and double-check every rm -rf.
  • systemctl enable controls boot behaviour; start and stop control the service right now.

Next in this series: Linux Users, Permissions and Package Management.