Presented at All Things Open 2025
Presented by Vladimir Levijev - Zabbix
Title: Linux command-line tips & tricks
Abstract: I will talk about things that might be useful when using GNU/Linux command-line. Be that scripting or just performing some manual tasks.
Find more info about All Things Op...
Presented at All Things Open 2025
Presented by Vladimir Levijev - Zabbix
Title: Linux command-line tips & tricks
Abstract: I will talk about things that might be useful when using GNU/Linux command-line. Be that scripting or just performing some manual tasks.
Find more info about All Things Open:
On the web: https://www.allthingsopen.org/
Twitter: https://twitter.com/AllThingsOpen
LinkedIn: https://www.linkedin.com/company/all-things-open/
Instagram: https://www.instagram.com/allthingsopen/
Facebook: https://www.facebook.com/AllThingsOpen
Mastodon: https://mastodon.social/@allthingsopen
Threads: https://www.threads.net/@allthingsopen
Bluesky: https://bsky.app/profile/allthingsopen.bsky.social
YouTube: https://www.youtube.com/@allthingsopen
2025 conference: https://2025.allthingsopen.org/
Size: 2.06 MB
Language: en
Added: Oct 20, 2025
Slides: 262 pages
Slide Content
Linux command-line tips & tricks
Vladimir Levijev (aka dimir)
October 13, 2025
1
Outline
Before we start
Introduction
What is Linux?
Some history
What is a Shell?
Basics about Shell
Shell environment
Bash commands
What is a script?
One-liners
The Bash script
Some more tricks?
Some tricks
2
Before we start
About myself
My name is Vladimir Levijev (aka dimir) I’ve been in IT for 24 years.
•Born in Tallinn,Estonia.
•Joined IT in 2001 (24 years), workingonly on GNU/Linuxsince.•Working as a C developer since 2003.•At the age of 29 moved toLatvia.•Working atZabbixas a C developer for the last 14 years.
3
About myself
My name is Vladimir Levijev (aka dimir) I’ve been in IT for 24 years.
•Born in Tallinn,Estonia.
•Joined IT in 2001 (24 years), workingonly on GNU/Linuxsince.•Working as a C developer since 2003.•At the age of 29 moved toLatvia.•Working atZabbixas a C developer for the last 14 years.
3
About myself
My name is Vladimir Levijev (aka dimir) I’ve been in IT for 24 years.
•Born in Tallinn,Estonia.
•Joined IT in 2001 (24 years), workingonly on GNU/Linuxsince.•Working as a C developer since 2003.•At the age of 29 moved toLatvia.•Working atZabbixas a C developer for the last 14 years.
3
About myself
My name is Vladimir Levijev (aka dimir) I’ve been in IT for 24 years.
•Born in Tallinn,Estonia.
•Joined IT in 2001 (24 years), workingonly on GNU/Linuxsince.•Working as a C developer since 2003.•At the age of 29 moved toLatvia.•Working atZabbixas a C developer for the last 14 years.
3
About myself
My name is Vladimir Levijev (aka dimir) I’ve been in IT for 24 years.
•Born in Tallinn,Estonia.
•Joined IT in 2001 (24 years), workingonly on GNU/Linuxsince.•Working as a C developer since 2003.•At the age of 29 moved toLatvia.•Working atZabbixas a C developer for the last 14 years.
3
About myself
My name is Vladimir Levijev (aka dimir) I’ve been in IT for 24 years.
•Born in Tallinn,Estonia.
•Joined IT in 2001 (24 years), workingonly on GNU/Linuxsince.•Working as a C developer since 2003.•At the age of 29 moved toLatvia.•Working atZabbixas a C developer for the last 14 years.
3
Location
Straight-line distance: 7,500 km (4,600 mi)
4
Land sizes
5
Population
6
Land area per person
7
Some facts
Estonia:
•Estonia has produced global tech companies likeSkype, TransferWise
(Wise), and Bolt.
•
Alfred Neuland won a gold medal (1920 Antwerp Olympics, Belgium)
inMen’s lightweight (67.5 kg) weightifting.
•First nation to offerInternet Voting(2005).
Latvia:
•
First Olympic Gold inMen’s BMXin 2008 in Beijing, M¯aris
Štrombergs.
•
First Olympic Gold in3x3 Basketballin 2024, Paris.
•
First LatvianOscar Winner (2025)for the animated filmFlow
(Latvian:Straume). 8
Some facts
Estonia:
•Estonia has produced global tech companies likeSkype, TransferWise
(Wise), and Bolt.
•
Alfred Neuland won a gold medal (1920 Antwerp Olympics, Belgium)
inMen’s lightweight (67.5 kg) weightifting.
•First nation to offerInternet Voting(2005).
Latvia:
•
First Olympic Gold inMen’s BMXin 2008 in Beijing, M¯aris
Štrombergs.
•
First Olympic Gold in3x3 Basketballin 2024, Paris.
•
First LatvianOscar Winner (2025)for the animated filmFlow
(Latvian:Straume). 8
About Zabbix
•100%Open Sourcemonitoring solution.
•The initial version 0.1 was released in 2001 underGPLv2.•The company with the same name was founded in 2005.•Has grown to 150 employees and 5 locations since including Latvia, Japan,
Brazil, Mexico, France.
•GPLv2 ->AGPLv3in 2024.•Features:
•Agent-based and Agentless monitoring
•Distributed •Automation (auto-discovery)•Visualization•Highly customizable•Global Footprint: Used by organizations in more than 160 countries,
serving both small businesses and global enterprises.
9
About Zabbix
•100%Open Sourcemonitoring solution.
•The initial version 0.1 was released in 2001 underGPLv2.•The company with the same name was founded in 2005.•Has grown to 150 employees and 5 locations since including Latvia, Japan,
Brazil, Mexico, France.
•GPLv2 ->AGPLv3in 2024.•Features:
•Agent-based and Agentless monitoring
•Distributed •Automation (auto-discovery)•Visualization•Highly customizable•Global Footprint: Used by organizations in more than 160 countries,
serving both small businesses and global enterprises.
9
About Zabbix
•100%Open Sourcemonitoring solution.
•The initial version 0.1 was released in 2001 underGPLv2.•The company with the same name was founded in 2005.•Has grown to 150 employees and 5 locations since including Latvia, Japan,
Brazil, Mexico, France.
•GPLv2 ->AGPLv3in 2024.•Features:
•Agent-based and Agentless monitoring
•Distributed •Automation (auto-discovery)•Visualization•Highly customizable•Global Footprint: Used by organizations in more than 160 countries,
serving both small businesses and global enterprises.
9
About Zabbix
•100%Open Sourcemonitoring solution.
•The initial version 0.1 was released in 2001 underGPLv2.•The company with the same name was founded in 2005.•Has grown to 150 employees and 5 locations since including Latvia, Japan,
Brazil, Mexico, France.
•GPLv2 ->AGPLv3in 2024.•Features:
•Agent-based and Agentless monitoring
•Distributed •Automation (auto-discovery)•Visualization•Highly customizable•Global Footprint: Used by organizations in more than 160 countries,
serving both small businesses and global enterprises.
9
About Zabbix
•100%Open Sourcemonitoring solution.
•The initial version 0.1 was released in 2001 underGPLv2.•The company with the same name was founded in 2005.•Has grown to 150 employees and 5 locations since including Latvia, Japan,
Brazil, Mexico, France.
•GPLv2 ->AGPLv3in 2024.•Features:
•Agent-based and Agentless monitoring
•Distributed •Automation (auto-discovery)•Visualization•Highly customizable•Global Footprint: Used by organizations in more than 160 countries,
serving both small businesses and global enterprises.
9
About Zabbix
•100%Open Sourcemonitoring solution.
•The initial version 0.1 was released in 2001 underGPLv2.•The company with the same name was founded in 2005.•Has grown to 150 employees and 5 locations since including Latvia, Japan,
Brazil, Mexico, France.
•GPLv2 ->AGPLv3in 2024.•Features:
•Agent-based and Agentless monitoring
•Distributed •Automation (auto-discovery)•Visualization•Highly customizable•Global Footprint: Used by organizations in more than 160 countries,
serving both small businesses and global enterprises.
9
About Zabbix
•100%Open Sourcemonitoring solution.
•The initial version 0.1 was released in 2001 underGPLv2.•The company with the same name was founded in 2005.•Has grown to 150 employees and 5 locations since including Latvia, Japan,
Brazil, Mexico, France.
•GPLv2 ->AGPLv3in 2024.•Features:
•Agent-based and Agentless monitoring
•Distributed •Automation (auto-discovery)•Visualization•Highly customizable•Global Footprint: Used by organizations in more than 160 countries,
serving both small businesses and global enterprises.
9
About Zabbix
•100%Open Sourcemonitoring solution.
•The initial version 0.1 was released in 2001 underGPLv2.•The company with the same name was founded in 2005.•Has grown to 150 employees and 5 locations since including Latvia, Japan,
Brazil, Mexico, France.
•GPLv2 ->AGPLv3in 2024.•Features:
•Agent-based and Agentless monitoring
•Distributed •Automation (auto-discovery)•Visualization•Highly customizable•Global Footprint: Used by organizations in more than 160 countries,
serving both small businesses and global enterprises.
9
About Zabbix
•100%Open Sourcemonitoring solution.
•The initial version 0.1 was released in 2001 underGPLv2.•The company with the same name was founded in 2005.•Has grown to 150 employees and 5 locations since including Latvia, Japan,
Brazil, Mexico, France.
•GPLv2 ->AGPLv3in 2024.•Features:
•Agent-based and Agentless monitoring
•Distributed •Automation (auto-discovery)•Visualization•Highly customizable•Global Footprint: Used by organizations in more than 160 countries,
serving both small businesses and global enterprises.
9
About Zabbix
•100%Open Sourcemonitoring solution.
•The initial version 0.1 was released in 2001 underGPLv2.•The company with the same name was founded in 2005.•Has grown to 150 employees and 5 locations since including Latvia, Japan,
Brazil, Mexico, France.
•GPLv2 ->AGPLv3in 2024.•Features:
•Agent-based and Agentless monitoring
•Distributed •Automation (auto-discovery)•Visualization•Highly customizable•Global Footprint: Used by organizations in more than 160 countries,
serving both small businesses and global enterprises.
9
About Zabbix
•100%Open Sourcemonitoring solution.
•The initial version 0.1 was released in 2001 underGPLv2.•The company with the same name was founded in 2005.•Has grown to 150 employees and 5 locations since including Latvia, Japan,
Brazil, Mexico, France.
•GPLv2 ->AGPLv3in 2024.•Features:
•Agent-based and Agentless monitoring
•Distributed •Automation (auto-discovery)•Visualization•Highly customizable•Global Footprint: Used by organizations in more than 160 countries,
serving both small businesses and global enterprises.
9
Zabbix company services
•Technical support
•Consulting•Training and certification•Turnkey solutions and implementation•Integration and custom development•Zabbix Cloud
10
Zabbix company services
•Technical support
•Consulting•Training and certification•Turnkey solutions and implementation•Integration and custom development•Zabbix Cloud
10
Zabbix company services
•Technical support
•Consulting•Training and certification•Turnkey solutions and implementation•Integration and custom development•Zabbix Cloud
10
Zabbix company services
•Technical support
•Consulting•Training and certification•Turnkey solutions and implementation•Integration and custom development•Zabbix Cloud
10
Zabbix company services
•Technical support
•Consulting•Training and certification•Turnkey solutions and implementation•Integration and custom development•Zabbix Cloud
10
Zabbix company services
•Technical support
•Consulting•Training and certification•Turnkey solutions and implementation•Integration and custom development•Zabbix Cloud
10
Zabbix company services
•Technical support
•Consulting•Training and certification•Turnkey solutions and implementation•Integration and custom development•Zabbix Cloud
10
What is Linux?
Linux documentaries
Recommended documentary movies about Linux:
The Code (2001)
Revolution OS (2001) 11
What is a Shell?
Without operating system
•Accessing the SATA controller
•Communicate with the controller via MMIO or I/O ports (usually protected
by the OS).
•Obtain access to hardware registers that control the SATA interface.
•Sending commands
•Construct and send ATA/ATAPI commands such asREAD SECTOR(S).
•Place command parameters into the controller’s command registers.
•Handling DMA or PIO transfers
•Use PIO to read/write data through CPU-accessible registers, or
•Set up DMA so the controller moves data directly into memory buffers.
•Waiting for status
•Poll or check status registers to determine readiness, completion, or errors.
•Handle and interpret controller/drive error bits if they appear.
•Reading the data
•Once transfer completes, access the memory buffer (or controller data
registers) to obtain raw sector bytes.
•Verify data integrity (e.g., via status or checksums if available).
•No filesystem support
•This method reads raw sectors — the program must implement filesystem
parsing (FAT, NTFS, ext, etc.) to locate a file’s sectors.
•There is nofopen/OS-level abstraction in this approach.
12
What is a Shell?
Operating systems provide variousservices to their users, including file
management, process management (running and terminating applications),
batch processing, and operating system monitoring and configuration.
The termshellin computing refers to an interface that allows a user to interact
with an operating system. There are two main types: command-line shells and
graphical shells.
13
Fist shells
•The first widely used UNIX shell was the Thompson shell (sh), created by
Ken Thompson around 1971 at Bell Labs.
•It was simple, mainly for running commands and basic scripting.•In 1977 at AT&T Bell Labs Stephen Bourne developed much more
powerfulBourne shell(also sh).
•1978 - C Shell (csh), C-like syntax•1980s - Korn Shell (ksh), TENEX C Shell (tcsh), Almquist Shell (ash)
•1980s - Z Shell (zsh), combining features from sh, ksh, and csh
•1989 - Brian Fox developedBourne Again Shell (bash), combines
features of sh and csh.
•Modern shells (bash, ksh, dash etc.) still maintain backwards compatibility
with sh.
14
Fist shells
•The first widely used UNIX shell was the Thompson shell (sh), created by
Ken Thompson around 1971 at Bell Labs.
•It was simple, mainly for running commands and basic scripting.•In 1977 at AT&T Bell Labs Stephen Bourne developed much more
powerfulBourne shell(also sh).
•1978 - C Shell (csh), C-like syntax•1980s - Korn Shell (ksh), TENEX C Shell (tcsh), Almquist Shell (ash)
•1980s - Z Shell (zsh), combining features from sh, ksh, and csh
•1989 - Brian Fox developedBourne Again Shell (bash), combines
features of sh and csh.
•Modern shells (bash, ksh, dash etc.) still maintain backwards compatibility
with sh.
14
Fist shells
•The first widely used UNIX shell was the Thompson shell (sh), created by
Ken Thompson around 1971 at Bell Labs.
•It was simple, mainly for running commands and basic scripting.•In 1977 at AT&T Bell Labs Stephen Bourne developed much more
powerfulBourne shell(also sh).
•1978 - C Shell (csh), C-like syntax•1980s - Korn Shell (ksh), TENEX C Shell (tcsh), Almquist Shell (ash)
•1980s - Z Shell (zsh), combining features from sh, ksh, and csh
•1989 - Brian Fox developedBourne Again Shell (bash), combines
features of sh and csh.
•Modern shells (bash, ksh, dash etc.) still maintain backwards compatibility
with sh.
14
Fist shells
•The first widely used UNIX shell was the Thompson shell (sh), created by
Ken Thompson around 1971 at Bell Labs.
•It was simple, mainly for running commands and basic scripting.•In 1977 at AT&T Bell Labs Stephen Bourne developed much more
powerfulBourne shell(also sh).
•1978 - C Shell (csh), C-like syntax•1980s - Korn Shell (ksh), TENEX C Shell (tcsh), Almquist Shell (ash)
•1980s - Z Shell (zsh), combining features from sh, ksh, and csh
•1989 - Brian Fox developedBourne Again Shell (bash), combines
features of sh and csh.
•Modern shells (bash, ksh, dash etc.) still maintain backwards compatibility
with sh.
14
Fist shells
•The first widely used UNIX shell was the Thompson shell (sh), created by
Ken Thompson around 1971 at Bell Labs.
•It was simple, mainly for running commands and basic scripting.•In 1977 at AT&T Bell Labs Stephen Bourne developed much more
powerfulBourne shell(also sh).
•1978 - C Shell (csh), C-like syntax•1980s - Korn Shell (ksh), TENEX C Shell (tcsh), Almquist Shell (ash)
•1980s - Z Shell (zsh), combining features from sh, ksh, and csh
•1989 - Brian Fox developedBourne Again Shell (bash), combines
features of sh and csh.
•Modern shells (bash, ksh, dash etc.) still maintain backwards compatibility
with sh.
14
Fist shells
•The first widely used UNIX shell was the Thompson shell (sh), created by
Ken Thompson around 1971 at Bell Labs.
•It was simple, mainly for running commands and basic scripting.•In 1977 at AT&T Bell Labs Stephen Bourne developed much more
powerfulBourne shell(also sh).
•1978 - C Shell (csh), C-like syntax•1980s - Korn Shell (ksh), TENEX C Shell (tcsh), Almquist Shell (ash)
•1980s - Z Shell (zsh), combining features from sh, ksh, and csh
•1989 - Brian Fox developedBourne Again Shell (bash), combines
features of sh and csh.
•Modern shells (bash, ksh, dash etc.) still maintain backwards compatibility
with sh.
14
Fist shells
•The first widely used UNIX shell was the Thompson shell (sh), created by
Ken Thompson around 1971 at Bell Labs.
•It was simple, mainly for running commands and basic scripting.•In 1977 at AT&T Bell Labs Stephen Bourne developed much more
powerfulBourne shell(also sh).
•1978 - C Shell (csh), C-like syntax•1980s - Korn Shell (ksh), TENEX C Shell (tcsh), Almquist Shell (ash)
•1980s - Z Shell (zsh), combining features from sh, ksh, and csh
•1989 - Brian Fox developedBourne Again Shell (bash), combines
features of sh and csh.
•Modern shells (bash, ksh, dash etc.) still maintain backwards compatibility
with sh.
14
Graphical shells
Graphical shells provide means for manipulating programs based on graphical
user interface (GUI).
Graphical shells are typically build on top of a windowing system. In case of
Linux it is usuallyX Window Systemand the shell consists of anX window
manager.
Some examples:
•KDE
•GNOME
•Xfce
15
Controlling command history
$ ls
$ ls
$ history | tail -3
498
499
500 history | tail -3
HISTCONTROL=ignoredups # ignore consecutive duplicates
HISTCONTROL=ignorespace # ignore commands that start with spaces
HISTCONTROL=ignoreboth # ignore both above mentioned
WithHISTCONTROL=ignoredups:
$ ls
$ ls
$ history | tail -3
498 cd
499ls
500 history | tail -3
17
Controlling command history
$ ls
$ ls
$ history | tail -3
498
499
500 history | tail -3
HISTCONTROL=ignoredups # ignore consecutive duplicates
HISTCONTROL=ignorespace # ignore commands that start with spaces
HISTCONTROL=ignoreboth # ignore both above mentioned
WithHISTCONTROL=ignoredups:
$ ls
$ ls
$ history | tail -3
498 cd
499ls
500 history | tail -3
17
Controlling command history
$ ls
$ ls
$ history | tail -3
498
499
500 history | tail -3
HISTCONTROL=ignoredups # ignore consecutive duplicates
HISTCONTROL=ignorespace # ignore commands that start with spaces
HISTCONTROL=ignoreboth # ignore both above mentioned
WithHISTCONTROL=ignoredups:
$ ls
$ ls
$ history | tail -3
498 cd
499ls
500 history | tail -3
17
Controlling command history
WithHISTCONTROL=ignorespace
$ ls
$ pwd
$ history | tail -3
498 cd
499 ls
500 history | tail -3
$ grep HIST ~/.bashrc
HISTCONTROL=ignoredups
Some other options:
HISTSIZE=500 # default
HISTFILE=~/.bash_history # default
HISTFILESIZE=500 # by default, the value of HISTSIZE
18
Controlling command history
WithHISTCONTROL=ignorespace
$ ls
$ pwd
$ history | tail -3
498 cd
499 ls
500 history | tail -3
$ grep HIST ~/.bashrc
HISTCONTROL=ignoredups
Some other options:
HISTSIZE=500 # default
HISTFILE=~/.bash_history # default
HISTFILESIZE=500 # by default, the value of HISTSIZE
18
Controlling command history
WithHISTCONTROL=ignorespace
$ ls
$ pwd
$ history | tail -3
498 cd
499 ls
500 history | tail -3
$ grep HIST ~/.bashrc
HISTCONTROL=ignoredups
Some other options:
HISTSIZE=500 # default
HISTFILE=~/.bash_history # default
HISTFILESIZE=500 # by default, the value of HISTSIZE
18
Bash aliases
$ alias
alias grep='grep --color=always'
alias less='less -R'
$ git diff --color linux-cmd.tex | less
ESC[1;33m--- a/linux-cmd.texESC[m
ESC[1;33m+++ b/linux-cmd.texESC[m
ESC[1;35m@@ -1,153 +1,321 @@ESC[m
ESC[1;31m-\documentclass{beamer}ESC[m
$ git diff --color linux-cmd.tex | less -R
--- a/linux-cmd.tex
+++ b/linux-cmd.tex
@@ -1,153 +1,321 @@
-\documentclass{beamer}
19
Bash aliases
$ alias
alias grep='grep --color=always'
alias less='less -R'
$ git diff --color linux-cmd.tex | less
ESC[1;33m--- a/linux-cmd.texESC[m
ESC[1;33m+++ b/linux-cmd.texESC[m
ESC[1;35m@@ -1,153 +1,321 @@ESC[m
ESC[1;31m-\documentclass{beamer}ESC[m
$ git diff --color linux-cmd.tex | less -R
--- a/linux-cmd.tex
+++ b/linux-cmd.tex
@@ -1,153 +1,321 @@
-\documentclass{beamer}
19
Bash aliases
$ alias
alias grep='grep --color=always'
alias less='less -R'
$ git diff --color linux-cmd.tex | less
ESC[1;33m--- a/linux-cmd.texESC[m
ESC[1;33m+++ b/linux-cmd.texESC[m
ESC[1;35m@@ -1,153 +1,321 @@ESC[m
ESC[1;31m-\documentclass{beamer}ESC[m
$ git diff --color linux-cmd.tex | less -R
--- a/linux-cmd.tex
+++ b/linux-cmd.tex
@@ -1,153 +1,321 @@
-\documentclass{beamer}
19
Me listing files
$ alias l='ls -lA --color'
-l use a long listing format
-A do not list implied . and ..
$ l -tr
-t sort by modification time, newest first
-r
$ l -tr ~/Downloads
[...]
linux-cmd.pdf
$
$ alias cl="find . -name'.#*'-o -name'*~'-o -name'#*#'
\,→
-o -name'*.rej'-o -name'*.orig'| xargs rm -fv"
$ cl
removed'./.#linux-cmd.tex.bak'
removed'./#linux-cmd.tex.bak#'
20
Me listing files
$ alias l='ls -lA --color'
-l use a long listing format
-A do not list implied . and ..
$ l -tr
-t sort by modification time, newest first
-r
$ l -tr ~/Downloads
[...]
linux-cmd.pdf
$
$ alias cl="find . -name'.#*'-o -name'*~'-o -name'#*#'
\,→
-o -name'*.rej'-o -name'*.orig'| xargs rm -fv"
$ cl
removed'./.#linux-cmd.tex.bak'
removed'./#linux-cmd.tex.bak#'
20
Me listing files
$ alias l='ls -lA --color'
-l use a long listing format
-A do not list implied . and ..
$ l -tr
-t sort by modification time, newest first
-r
$ l -tr ~/Downloads
[...]
linux-cmd.pdf
$
$ alias cl="find . -name'.#*'-o -name'*~'-o -name'#*#'
\,→
-o -name'*.rej'-o -name'*.orig'| xargs rm -fv"
$ cl
removed'./.#linux-cmd.tex.bak'
removed'./#linux-cmd.tex.bak#'
20
Me listing files
$ alias l='ls -lA --color'
-l use a long listing format
-A do not list implied . and ..
$ l -tr
-t sort by modification time, newest first
-r
$ l -tr ~/Downloads
[...]
linux-cmd.pdf
$
$ alias cl="find . -name'.#*'-o -name'*~'-o -name'#*#'
\,→
-o -name'*.rej'-o -name'*.orig'| xargs rm -fv"
$ cl
removed'./.#linux-cmd.tex.bak'
removed'./#linux-cmd.tex.bak#'
20
Searching through history
$ history | tail -3
592 l -tr ~/Downloads
593 cd -
594 locate -i --regex'zbxnext.*\.patch'
For searching a command you typed some time ago hitCtrl+rand type part of
it that you remember:
Ctrl+r <PATTERN>
More Ctrl+r to go to next match
E. g.: searching for command that contained "loca":
(reverse-i-search)`loca': locate -i --regex'zbxnext.*\.patch'
21
Searching through history
$ history | tail -3
592 l -tr ~/Downloads
593 cd -
594 locate -i --regex'zbxnext.*\.patch'
For searching a command you typed some time ago hitCtrl+rand type part of
it that you remember:
Ctrl+r <PATTERN>
More Ctrl+r to go to next match
E. g.: searching for command that contained "loca":
(reverse-i-search)`loca': locate -i --regex'zbxnext.*\.patch'
21
Searching through history
$ history | tail -3
592 l -tr ~/Downloads
593 cd -
594 locate -i --regex'zbxnext.*\.patch'
For searching a command you typed some time ago hitCtrl+rand type part of
it that you remember:
Ctrl+r <PATTERN>
More Ctrl+r to go to next match
E. g.: searching for command that contained "loca":
(reverse-i-search)`loca': locate -i --regex'zbxnext.*\.patch'
21
Searching through history
$ history | tail -3
592 l -tr ~/Downloads
593 cd -
594 locate -i --regex'zbxnext.*\.patch'
For searching a command you typed some time ago hitCtrl+rand type part of
it that you remember:
Ctrl+r <PATTERN>
More Ctrl+r to go to next match
E. g.: searching for command that contained "loca":
(reverse-i-search)`loca': locate -i --regex'zbxnext.*\.patch'
21
XON/XOFF flow control
In Unix-like terminals, Ctrl+S and Ctrl+Q are part of the classic XON/XOFF
flow control.
1. →"stop output"
2.3.
to Ctrl+C)
4. →"resume output"5.
•If you accidentally hit Ctrl+S, the terminal looks "frozen" but the program
is still running. Pressing Ctrl+Q unfreezes it.
•You can disable this behavior with:
$ stty -ixon
then Ctrl+S and Ctrl+Q won’t pause/resume output anymore
22
XON/XOFF flow control
In Unix-like terminals, Ctrl+S and Ctrl+Q are part of the classic XON/XOFF
flow control.
1. →"stop output"
2.3.
to Ctrl+C)
4. →"resume output"5.
•If you accidentally hit Ctrl+S, the terminal looks "frozen" but the program
is still running. Pressing Ctrl+Q unfreezes it.
•You can disable this behavior with:
$ stty -ixon
then Ctrl+S and Ctrl+Q won’t pause/resume output anymore
22
XON/XOFF flow control
In Unix-like terminals, Ctrl+S and Ctrl+Q are part of the classic XON/XOFF
flow control.
1. →"stop output"
2.3.
to Ctrl+C)
4. →"resume output"5.
•If you accidentally hit Ctrl+S, the terminal looks "frozen" but the program
is still running. Pressing Ctrl+Q unfreezes it.
•You can disable this behavior with:
$ stty -ixon
then Ctrl+S and Ctrl+Q won’t pause/resume output anymore
22
XON/XOFF flow control
In Unix-like terminals, Ctrl+S and Ctrl+Q are part of the classic XON/XOFF
flow control.
1. →"stop output"
2.3.
to Ctrl+C)
4. →"resume output"5.
•If you accidentally hit Ctrl+S, the terminal looks "frozen" but the program
is still running. Pressing Ctrl+Q unfreezes it.
•You can disable this behavior with:
$ stty -ixon
then Ctrl+S and Ctrl+Q won’t pause/resume output anymore
22
XON/XOFF flow control
In Unix-like terminals, Ctrl+S and Ctrl+Q are part of the classic XON/XOFF
flow control.
1. →"stop output"
2.3.
to Ctrl+C)
4. →"resume output"5.
•If you accidentally hit Ctrl+S, the terminal looks "frozen" but the program
is still running. Pressing Ctrl+Q unfreezes it.
•You can disable this behavior with:
$ stty -ixon
then Ctrl+S and Ctrl+Q won’t pause/resume output anymore
22
XON/XOFF flow control
In Unix-like terminals, Ctrl+S and Ctrl+Q are part of the classic XON/XOFF
flow control.
1. →"stop output"
2.3.
to Ctrl+C)
4. →"resume output"5.
•If you accidentally hit Ctrl+S, the terminal looks "frozen" but the program
is still running. Pressing Ctrl+Q unfreezes it.
•You can disable this behavior with:
$ stty -ixon
then Ctrl+S and Ctrl+Q won’t pause/resume output anymore
22
XON/XOFF flow control
In Unix-like terminals, Ctrl+S and Ctrl+Q are part of the classic XON/XOFF
flow control.
1. →"stop output"
2.3.
to Ctrl+C)
4. →"resume output"5.
•If you accidentally hit Ctrl+S, the terminal looks "frozen" but the program
is still running. Pressing Ctrl+Q unfreezes it.
•You can disable this behavior with:
$ stty -ixon
then Ctrl+S and Ctrl+Q won’t pause/resume output anymore
22
XON/XOFF flow control
In Unix-like terminals, Ctrl+S and Ctrl+Q are part of the classic XON/XOFF
flow control.
1. →"stop output"
2.3.
to Ctrl+C)
4. →"resume output"5.
•If you accidentally hit Ctrl+S, the terminal looks "frozen" but the program
is still running. Pressing Ctrl+Q unfreezes it.
•You can disable this behavior with:
$ stty -ixon
then Ctrl+S and Ctrl+Q won’t pause/resume output anymore
22
Clearing the terminal screen
Clearing the terminal in Linux can be done in several ways, depending on what
you want to achieve.
•Purpose:clears the visible terminal screen
•How it works:moves all previous output off-screen but doesn’t remove it
from the terminal’s scrollback buffer soyou can still scroll upto see it
•Usage:
$ clear
•Shortcult: Ctrl+L
Sometimes you get garbled text on the screen and clearing doesn’t help. In such
case you need to fully reset the terminal.
•Purpose:reset the terminal session
•How it works:resets the terminal modes, colors and settings, clears
garbled text
•Usage:
$ cat /dev/random | head
[...]
•�*��+��,�reset
23
Clearing the terminal screen
Clearing the terminal in Linux can be done in several ways, depending on what
you want to achieve.
•Purpose:clears the visible terminal screen
•How it works:moves all previous output off-screen but doesn’t remove it
from the terminal’s scrollback buffer soyou can still scroll upto see it
•Usage:
$ clear
•Shortcult: Ctrl+L
Sometimes you get garbled text on the screen and clearing doesn’t help. In such
case you need to fully reset the terminal.
•Purpose:reset the terminal session
•How it works:resets the terminal modes, colors and settings, clears
garbled text
•Usage:
$ cat /dev/random | head
[...]
•�*��+��,�reset
23
Clearing the terminal screen
Clearing the terminal in Linux can be done in several ways, depending on what
you want to achieve.
•Purpose:clears the visible terminal screen
•How it works:moves all previous output off-screen but doesn’t remove it
from the terminal’s scrollback buffer soyou can still scroll upto see it
•Usage:
$ clear
•Shortcult: Ctrl+L
Sometimes you get garbled text on the screen and clearing doesn’t help. In such
case you need to fully reset the terminal.
•Purpose:reset the terminal session
•How it works:resets the terminal modes, colors and settings, clears
garbled text
•Usage:
$ cat /dev/random | head
[...]
•�*��+��,�reset
23
Clearing the terminal screen
Clearing the terminal in Linux can be done in several ways, depending on what
you want to achieve.
•Purpose:clears the visible terminal screen
•How it works:moves all previous output off-screen but doesn’t remove it
from the terminal’s scrollback buffer soyou can still scroll upto see it
•Usage:
$ clear
•Shortcult: Ctrl+L
Sometimes you get garbled text on the screen and clearing doesn’t help. In such
case you need to fully reset the terminal.
•Purpose:reset the terminal session
•How it works:resets the terminal modes, colors and settings, clears
garbled text
•Usage:
$ cat /dev/random | head
[...]
•�*��+��,�reset
23
Who am I?
$ whoami
vl
$ echo $USER
vl
$ id
uid=1000(vl) gid=1000(vl) groups=1000(vl),4(adm),999(docker)
$ id -u
1000
$ lastlog -u vl
Username Port From Latest
vl pts/4 192.168.3.68 Tue Jan 16 09:40:05
24
Who am I?
$ whoami
vl
$ echo $USER
vl
$ id
uid=1000(vl) gid=1000(vl) groups=1000(vl),4(adm),999(docker)
$ id -u
1000
$ lastlog -u vl
Username Port From Latest
vl pts/4 192.168.3.68 Tue Jan 16 09:40:05
24
Who am I?
$ whoami
vl
$ echo $USER
vl
$ id
uid=1000(vl) gid=1000(vl) groups=1000(vl),4(adm),999(docker)
$ id -u
1000
$ lastlog -u vl
Username Port From Latest
vl pts/4 192.168.3.68 Tue Jan 16 09:40:05
24
Who am I?
$ whoami
vl
$ echo $USER
vl
$ id
uid=1000(vl) gid=1000(vl) groups=1000(vl),4(adm),999(docker)
$ id -u
1000
$ lastlog -u vl
Username Port From Latest
vl pts/4 192.168.3.68 Tue Jan 16 09:40:05
24
Who am I?
$ whoami
vl
$ echo $USER
vl
$ id
uid=1000(vl) gid=1000(vl) groups=1000(vl),4(adm),999(docker)
$ id -u
1000
$ lastlog -u vl
Username Port From Latest
vl pts/4 192.168.3.68 Tue Jan 16 09:40:05
24
What is my Shell?
$ echo $SHELL
/bin/bash
$ grep vl /etc/passwd
vl:x:1000:1000:Vladimir Levijev,,,:/home/vl:/bin/bash
$ chsh
Password:
Changing the login shell for vl
Enter the new value, or press ENTER for the default
Login Shell [/bin/bash]:
25
What is my Shell?
$ echo $SHELL
/bin/bash
$ grep vl /etc/passwd
vl:x:1000:1000:Vladimir Levijev,,,:/home/vl:/bin/bash
$ chsh
Password:
Changing the login shell for vl
Enter the new value, or press ENTER for the default
Login Shell [/bin/bash]:
25
What is my Shell?
$ echo $SHELL
/bin/bash
$ grep vl /etc/passwd
vl:x:1000:1000:Vladimir Levijev,,,:/home/vl:/bin/bash
$ chsh
Password:
Changing the login shell for vl
Enter the new value, or press ENTER for the default
Login Shell [/bin/bash]:
25
Where am I?
Debian:
$ cat /etc/timezone
Europe/Riga
RedHat:
$ readlink /etc/localtime
../usr/share/zoneinfo/Europe/Riga
$ timedatectl
Local time: Sun 2025-10-12 20:43:49 EEST
Universal time: Sun 2025-10-12 17:43:49 UTC
RTC time: Sun 2025-10-12 17:43:49
Time zone: Europe/Riga (EEST, +0300)
System clock synchronized: yes
27
Where am I?
Debian:
$ cat /etc/timezone
Europe/Riga
RedHat:
$ readlink /etc/localtime
../usr/share/zoneinfo/Europe/Riga
$ timedatectl
Local time: Sun 2025-10-12 20:43:49 EEST
Universal time: Sun 2025-10-12 17:43:49 UTC
RTC time: Sun 2025-10-12 17:43:49
Time zone: Europe/Riga (EEST, +0300)
System clock synchronized: yes
27
Where I just was?
$ echo $OLDPWD
/etc
$ env | grep WD
OLDPWD=/etc
PWD=/home/vl
$ cd -
-is not a regular argument — it’s a special option/operand tocd
that means "previous working directory" ($OLDPWD)
$ ls -
ls: cannot access'-': No such file or directory
$ export OLDPWD=/tmp/non-existent
$ cd -
-bash: cd: /tmp/non-existent: No such file or directory
28
Where I just was?
$ echo $OLDPWD
/etc
$ env | grep WD
OLDPWD=/etc
PWD=/home/vl
$ cd -
-is not a regular argument — it’s a special option/operand tocd
that means "previous working directory" ($OLDPWD)
$ ls -
ls: cannot access'-': No such file or directory
$ export OLDPWD=/tmp/non-existent
$ cd -
-bash: cd: /tmp/non-existent: No such file or directory
28
Where I just was?
$ echo $OLDPWD
/etc
$ env | grep WD
OLDPWD=/etc
PWD=/home/vl
$ cd -
-is not a regular argument — it’s a special option/operand tocd
that means "previous working directory" ($OLDPWD)
$ ls -
ls: cannot access'-': No such file or directory
$ export OLDPWD=/tmp/non-existent
$ cd -
-bash: cd: /tmp/non-existent: No such file or directory
28
Where I just was?
$ echo $OLDPWD
/etc
$ env | grep WD
OLDPWD=/etc
PWD=/home/vl
$ cd -
-is not a regular argument — it’s a special option/operand tocd
that means "previous working directory" ($OLDPWD)
$ ls -
ls: cannot access'-': No such file or directory
$ export OLDPWD=/tmp/non-existent
$ cd -
-bash: cd: /tmp/non-existent: No such file or directory
28
Where I just was?
$ echo $OLDPWD
/etc
$ env | grep WD
OLDPWD=/etc
PWD=/home/vl
$ cd -
-is not a regular argument — it’s a special option/operand tocd
that means "previous working directory" ($OLDPWD)
$ ls -
ls: cannot access'-': No such file or directory
$ export OLDPWD=/tmp/non-existent
$ cd -
-bash: cd: /tmp/non-existent: No such file or directory
28
Environment variable glitch
$ USERNAME=john echo "USERNAME=$USERNAME"
USERNAME=$ USERNAME=john;echo "USERNAME=$USERNAME"
USERNAME=john
•USERNAME=johnin the first case setsenvironment variableforecho
•But before launching the command, the shell (your running shell) first
parses andexpands argumentsUSERNAME=$USERNAME.
•Since current shell session has no idea about this variable it expands it to
USERNAME=.
After expanding the arguments shell calls:
$ USERNAME=john echo "USERNAME="
$ USERNAME=john sh -c'echo "USERNAME=$USERNAME"'
USERNAME=john
29
Environment variable glitch
$ USERNAME=john echo "USERNAME=$USERNAME"
USERNAME=$ USERNAME=john;echo "USERNAME=$USERNAME"
USERNAME=john
•USERNAME=johnin the first case setsenvironment variableforecho
•But before launching the command, the shell (your running shell) first
parses andexpands argumentsUSERNAME=$USERNAME.
•Since current shell session has no idea about this variable it expands it to
USERNAME=.
After expanding the arguments shell calls:
$ USERNAME=john echo "USERNAME="
$ USERNAME=john sh -c'echo "USERNAME=$USERNAME"'
USERNAME=john
29
Environment variable glitch
$ USERNAME=john echo "USERNAME=$USERNAME"
USERNAME=$ USERNAME=john;echo "USERNAME=$USERNAME"
USERNAME=john
•USERNAME=johnin the first case setsenvironment variableforecho
•But before launching the command, the shell (your running shell) first
parses andexpands argumentsUSERNAME=$USERNAME.
•Since current shell session has no idea about this variable it expands it to
USERNAME=.
After expanding the arguments shell calls:
$ USERNAME=john echo "USERNAME="
$ USERNAME=john sh -c'echo "USERNAME=$USERNAME"'
USERNAME=john
29
Environment variable glitch
$ USERNAME=john echo "USERNAME=$USERNAME"
USERNAME=$ USERNAME=john;echo "USERNAME=$USERNAME"
USERNAME=john
•USERNAME=johnin the first case setsenvironment variableforecho
•But before launching the command, the shell (your running shell) first
parses andexpands argumentsUSERNAME=$USERNAME.
•Since current shell session has no idea about this variable it expands it to
USERNAME=.
After expanding the arguments shell calls:
$ USERNAME=john echo "USERNAME="
$ USERNAME=john sh -c'echo "USERNAME=$USERNAME"'
USERNAME=john
29
Environment variable glitch
$ USERNAME=john echo "USERNAME=$USERNAME"
USERNAME=$ USERNAME=john;echo "USERNAME=$USERNAME"
USERNAME=john
•USERNAME=johnin the first case setsenvironment variableforecho
•But before launching the command, the shell (your running shell) first
parses andexpands argumentsUSERNAME=$USERNAME.
•Since current shell session has no idea about this variable it expands it to
USERNAME=.
After expanding the arguments shell calls:
$ USERNAME=john echo "USERNAME="
$ USERNAME=john sh -c'echo "USERNAME=$USERNAME"'
USERNAME=john
29
Environment variable glitch
$ USERNAME=john echo "USERNAME=$USERNAME"
USERNAME=$ USERNAME=john;echo "USERNAME=$USERNAME"
USERNAME=john
•USERNAME=johnin the first case setsenvironment variableforecho
•But before launching the command, the shell (your running shell) first
parses andexpands argumentsUSERNAME=$USERNAME.
•Since current shell session has no idea about this variable it expands it to
USERNAME=.
After expanding the arguments shell calls:
$ USERNAME=john echo "USERNAME="
$ USERNAME=john sh -c'echo "USERNAME=$USERNAME"'
USERNAME=john
29
Environment variable glitch
$ USERNAME=john echo "USERNAME=$USERNAME"
USERNAME=$ USERNAME=john;echo "USERNAME=$USERNAME"
USERNAME=john
•USERNAME=johnin the first case setsenvironment variableforecho
•But before launching the command, the shell (your running shell) first
parses andexpands argumentsUSERNAME=$USERNAME.
•Since current shell session has no idea about this variable it expands it to
USERNAME=.
After expanding the arguments shell calls:
$ USERNAME=john echo "USERNAME="
$ USERNAME=john sh -c'echo "USERNAME=$USERNAME"'
USERNAME=john
29
Environment variable glitch
$ USERNAME=john echo "USERNAME=$USERNAME"
USERNAME=$ USERNAME=john;echo "USERNAME=$USERNAME"
USERNAME=john
•USERNAME=johnin the first case setsenvironment variableforecho
•But before launching the command, the shell (your running shell) first
parses andexpands argumentsUSERNAME=$USERNAME.
•Since current shell session has no idea about this variable it expands it to
USERNAME=.
After expanding the arguments shell calls:
$ USERNAME=john echo "USERNAME="
$ USERNAME=john sh -c'echo "USERNAME=$USERNAME"'
USERNAME=john
29
Where can I go?
Home!
$ cd
~$
Alternatives:
$ cd $HOME
$ cd ~
the tilde~is not specific tocd, it’s handled by the shell itself
Parent directory!
~$ cd ..
/home
Stay where you are.
$ cd .
/home
30
Where can I go?
Home!
$ cd
~$
Alternatives:
$ cd $HOME
$ cd ~
the tilde~is not specific tocd, it’s handled by the shell itself
Parent directory!
~$ cd ..
/home
Stay where you are.
$ cd .
/home
30
Where can I go?
Home!
$ cd
~$
Alternatives:
$ cd $HOME
$ cd ~
the tilde~is not specific tocd, it’s handled by the shell itself
Parent directory!
~$ cd ..
/home
Stay where you are.
$ cd .
/home
30
Where can I go?
Home!
$ cd
~$
Alternatives:
$ cd $HOME
$ cd ~
the tilde~is not specific tocd, it’s handled by the shell itself
Parent directory!
~$ cd ..
/home
Stay where you are.
$ cd .
/home
30
How locate works
/var/lib/plocate/plocate.db
•specific binary format
•zstd compressed
•fasterthanmlocate, might be notable on big systems with millions of files
32
Listing directory permissions
$ ls -l /var/lib/mysql
drwx------ 2 mysql mysql 4096 May 3 2023 zabbix6_0
drwx------ 2 mysql mysql 4096 Jun 15 2024 zabbix7_0$ ls -l /var/lib | grep mysql
drwxr-xr-x 33 mysql mysql 4096 Sep 22 14:01 mysql
drwx------ 2 mysql mysql 4096 Dec 8 2016
-rw-rw---- 1
-rw-rw---- 1
$ ls -l /var/lib | grep'mysql$'
drwxr-xr-x 33 mysql mysql 4096 Sep 22 14:01 mysql
$ ls --color -l /var/lib | grep'mysql$'
$
$ ls -l
drwxr-xr-x 33 mysql mysql 4096 Sep 22 14:01
-d, --directorylist directories themselves, not their contents
33
Listing directory permissions
$ ls -l /var/lib/mysql
drwx------ 2 mysql mysql 4096 May 3 2023 zabbix6_0
drwx------ 2 mysql mysql 4096 Jun 15 2024 zabbix7_0$ ls -l /var/lib | grep mysql
drwxr-xr-x 33 mysql mysql 4096 Sep 22 14:01 mysql
drwx------ 2 mysql mysql 4096 Dec 8 2016
-rw-rw---- 1
-rw-rw---- 1
$ ls -l /var/lib | grep'mysql$'
drwxr-xr-x 33 mysql mysql 4096 Sep 22 14:01 mysql
$ ls --color -l /var/lib | grep'mysql$'
$
$ ls -l
drwxr-xr-x 33 mysql mysql 4096 Sep 22 14:01
-d, --directorylist directories themselves, not their contents
33
Listing directory permissions
$ ls -l /var/lib/mysql
drwx------ 2 mysql mysql 4096 May 3 2023 zabbix6_0
drwx------ 2 mysql mysql 4096 Jun 15 2024 zabbix7_0$ ls -l /var/lib | grep mysql
drwxr-xr-x 33 mysql mysql 4096 Sep 22 14:01 mysql
drwx------ 2 mysql mysql 4096 Dec 8 2016
-rw-rw---- 1
-rw-rw---- 1
$ ls -l /var/lib | grep'mysql$'
drwxr-xr-x 33 mysql mysql 4096 Sep 22 14:01 mysql
$ ls --color -l /var/lib | grep'mysql$'
$
$ ls -l
drwxr-xr-x 33 mysql mysql 4096 Sep 22 14:01
-d, --directorylist directories themselves, not their contents
33
Listing directory permissions
$ ls -l /var/lib/mysql
drwx------ 2 mysql mysql 4096 May 3 2023 zabbix6_0
drwx------ 2 mysql mysql 4096 Jun 15 2024 zabbix7_0$ ls -l /var/lib | grep mysql
drwxr-xr-x 33 mysql mysql 4096 Sep 22 14:01 mysql
drwx------ 2 mysql mysql 4096 Dec 8 2016
-rw-rw---- 1
-rw-rw---- 1
$ ls -l /var/lib | grep'mysql$'
drwxr-xr-x 33 mysql mysql 4096 Sep 22 14:01 mysql
$ ls --color -l /var/lib | grep'mysql$'
$
$ ls -l
drwxr-xr-x 33 mysql mysql 4096 Sep 22 14:01
-d, --directorylist directories themselves, not their contents
33
Listing directory permissions
$ ls -l /var/lib/mysql
drwx------ 2 mysql mysql 4096 May 3 2023 zabbix6_0
drwx------ 2 mysql mysql 4096 Jun 15 2024 zabbix7_0$ ls -l /var/lib | grep mysql
drwxr-xr-x 33 mysql mysql 4096 Sep 22 14:01 mysql
drwx------ 2 mysql mysql 4096 Dec 8 2016
-rw-rw---- 1
-rw-rw---- 1
$ ls -l /var/lib | grep'mysql$'
drwxr-xr-x 33 mysql mysql 4096 Sep 22 14:01 mysql
$ ls --color -l /var/lib | grep'mysql$'
$
$ ls -l
drwxr-xr-x 33 mysql mysql 4096 Sep 22 14:01
-d, --directorylist directories themselves, not their contents
33
Listing directory permissions
$ ls -l /var/lib/mysql
drwx------ 2 mysql mysql 4096 May 3 2023 zabbix6_0
drwx------ 2 mysql mysql 4096 Jun 15 2024 zabbix7_0$ ls -l /var/lib | grep mysql
drwxr-xr-x 33 mysql mysql 4096 Sep 22 14:01 mysql
drwx------ 2 mysql mysql 4096 Dec 8 2016
-rw-rw---- 1
-rw-rw---- 1
$ ls -l /var/lib | grep'mysql$'
drwxr-xr-x 33 mysql mysql 4096 Sep 22 14:01 mysql
$ ls --color -l /var/lib | grep'mysql$'
$
$ ls -l
drwxr-xr-x 33 mysql mysql 4096 Sep 22 14:01
-d, --directorylist directories themselves, not their contents
33
Securing files
$ echo pass123 > secret.pw
-rw-r––r–– 1 vl adm 8 Jan 25 16:35 secret.pw
$ umask
0022
New files : 666 – 022 = 644
New directories : 777 – 022 = 755
The first digit in a umask value (if present) controls special permission bits:
•0 — no special restrictions
•1 — disables the sticky bit
•2 — disables the setgid bit
•4 — disables the setuid bit
These bits are rarely masked, so the first digit is usually 0.
34
Securing files
$ echo pass123 > secret.pw
-rw-r––r–– 1 vl adm 8 Jan 25 16:35 secret.pw
$ umask
0022
New files : 666 – 022 = 644
New directories : 777 – 022 = 755
The first digit in a umask value (if present) controls special permission bits:
•0 — no special restrictions
•1 — disables the sticky bit
•2 — disables the setgid bit
•4 — disables the setuid bit
These bits are rarely masked, so the first digit is usually 0.
34
Securing files
$ echo pass123 > secret.pw
-rw-r––r–– 1 vl adm 8 Jan 25 16:35 secret.pw
$ umask
0022
New files : 666 – 022 = 644
New directories : 777 – 022 = 755
The first digit in a umask value (if present) controls special permission bits:
•0 — no special restrictions
•1 — disables the sticky bit
•2 — disables the setgid bit
•4 — disables the setuid bit
These bits are rarely masked, so the first digit is usually 0.
34
Securing files
$ echo pass123 > secret.pw
-rw-r––r–– 1 vl adm 8 Jan 25 16:35 secret.pw
$ umask
0022
New files : 666 – 022 = 644
New directories : 777 – 022 = 755
The first digit in a umask value (if present) controls special permission bits:
•0 — no special restrictions
•1 — disables the sticky bit
•2 — disables the setgid bit
•4 — disables the setuid bit
These bits are rarely masked, so the first digit is usually 0.
34
Appending to a file
$ l secret.pw
-rw------- 1
$ echo foobar >> secret.pw
-bash: secret.pw: Permission denied
$ sudo echo foobar >> secret.pw
-bash: secret.pw: Permission denied
Who handles the redirection?
•The>> secret.pwredirection is handled by your shell, before sudo is
applied.
•sudoonly applies toecho, not to the redirection.
36
Appending to a file
$ l secret.pw
-rw------- 1
$ echo foobar >> secret.pw
-bash: secret.pw: Permission denied
$ sudo echo foobar >> secret.pw
-bash: secret.pw: Permission denied
Who handles the redirection?
•The>> secret.pwredirection is handled by your shell, before sudo is
applied.
•sudoonly applies toecho, not to the redirection.
36
Appending to a file
$ l secret.pw
-rw------- 1
$ echo foobar >> secret.pw
-bash: secret.pw: Permission denied
$ sudo echo foobar >> secret.pw
-bash: secret.pw: Permission denied
Who handles the redirection?
•The>> secret.pwredirection is handled by your shell, before sudo is
applied.
•sudoonly applies toecho, not to the redirection.
36
Appending to a file
$ l secret.pw
-rw------- 1
$ echo foobar >> secret.pw
-bash: secret.pw: Permission denied
$ sudo echo foobar >> secret.pw
-bash: secret.pw: Permission denied
Who handles the redirection?
•The>> secret.pwredirection is handled by your shell, before sudo is
applied.
•sudoonly applies toecho, not to the redirection.
36
Appending to a file
$ echo foobar | sudo
foobar
-a, --append
append to the given FILEs, do not overwrite$ sudo cat secret.pw
pass123
foobar
37
Appending to a file
$ echo foobar | sudo
foobar
-a, --append
append to the given FILEs, do not overwrite$ sudo cat secret.pw
pass123
foobar
37
File attributes
In Linux, file attributes are special flags that controladditional behaviorsof
files and directories beyond the normal read, write, and execute permissions.
These are supported on ext2, ext3, ext4, and some other file systems.
Key points:
•Independent of permissions
•Persistent at the filesystem level
•Attributes control:
•Modification
•Access time updates
•Deletion behavior
•Compression
•Analogy:
•Permissions = keys to the cabinet with documents
•Attributes = seals, instructions on the document
38
Securing a file
$ lsattr /etc/passwd
--------------e------- /etc/passwd
$ echo -n --------------e------- | wc -c
22
A file with the ’i’ attributecannot be modified: it cannot be deleted or re-
named, no link can be created to this file.
$ sudo chattr +i /etc/passwd
$ lsattr /etc/passwd
----i---------e------- /etc/passwd
$ sudo useradd -M -r -s /usr/sbin/nologin tempuser
useradd: cannot open /etc/passwd$ sudo chattr -i /etc/passwd
39
Securing a file
$ lsattr /etc/passwd
--------------e------- /etc/passwd
$ echo -n --------------e------- | wc -c
22
A file with the ’i’ attributecannot be modified: it cannot be deleted or re-
named, no link can be created to this file.
$ sudo chattr +i /etc/passwd
$ lsattr /etc/passwd
----i---------e------- /etc/passwd
$ sudo useradd -M -r -s /usr/sbin/nologin tempuser
useradd: cannot open /etc/passwd$ sudo chattr -i /etc/passwd
39
Securing a file
$ lsattr /etc/passwd
--------------e------- /etc/passwd
$ echo -n --------------e------- | wc -c
22
A file with the ’i’ attributecannot be modified: it cannot be deleted or re-
named, no link can be created to this file.
$ sudo chattr +i /etc/passwd
$ lsattr /etc/passwd
----i---------e------- /etc/passwd
$ sudo useradd -M -r -s /usr/sbin/nologin tempuser
useradd: cannot open /etc/passwd$ sudo chattr -i /etc/passwd
39
Securing a file
$ lsattr /etc/passwd
--------------e------- /etc/passwd
$ echo -n --------------e------- | wc -c
22
A file with the ’i’ attributecannot be modified: it cannot be deleted or re-
named, no link can be created to this file.
$ sudo chattr +i /etc/passwd
$ lsattr /etc/passwd
----i---------e------- /etc/passwd
$ sudo useradd -M -r -s /usr/sbin/nologin tempuser
useradd: cannot open /etc/passwd$ sudo chattr -i /etc/passwd
39
Securing a file
$ lsattr /etc/passwd
--------------e------- /etc/passwd
$ echo -n --------------e------- | wc -c
22
A file with the ’i’ attributecannot be modified: it cannot be deleted or re-
named, no link can be created to this file.
$ sudo chattr +i /etc/passwd
$ lsattr /etc/passwd
----i---------e------- /etc/passwd
$ sudo useradd -M -r -s /usr/sbin/nologin tempuser
useradd: cannot open /etc/passwd$ sudo chattr -i /etc/passwd
39
Securing a file
$ lsattr /etc/passwd
--------------e------- /etc/passwd
$ echo -n --------------e------- | wc -c
22
A file with the ’i’ attributecannot be modified: it cannot be deleted or re-
named, no link can be created to this file.
$ sudo chattr +i /etc/passwd
$ lsattr /etc/passwd
----i---------e------- /etc/passwd
$ sudo useradd -M -r -s /usr/sbin/nologin tempuser
useradd: cannot open /etc/passwd$ sudo chattr -i /etc/passwd
39
Securing a file
$ whoami
vl
$ touch /tmp/foo
$ chattr +i /tmp/foo
Pchattr: Operation not permitted while setting flags on /tmp/foo
40
Common filesystem attributes
AttributeEffect
i Immutable: cannot modify, delete, or rename
a Append-only: can only add data
A No atime updates: read does not change access time
c Compressed: filesystem handles compression
s Secure deletion: wiped securely when deleted
$ sudo tune2fs -l /dev/sda3 | grep'Filesystem features'
Filesystem features: has_journal ext_attr resize_inode
dir_index filetype needs_recovery extent 64bit flex_bg
sparse_super large_file huge_file dir_nlink extra_isize
metadata_csum
,→
,→
,→
$ sudo tune2fs -l /dev/sda3 | grep'Filesystem features'|
grep compress,→
$
41
Common filesystem attributes
AttributeEffect
i Immutable: cannot modify, delete, or rename
a Append-only: can only add data
A No atime updates: read does not change access time
c Compressed: filesystem handles compression
s Secure deletion: wiped securely when deleted
$ sudo tune2fs -l /dev/sda3 | grep'Filesystem features'
Filesystem features: has_journal ext_attr resize_inode
dir_index filetype needs_recovery extent 64bit flex_bg
sparse_super large_file huge_file dir_nlink extra_isize
metadata_csum
,→
,→
,→
$ sudo tune2fs -l /dev/sda3 | grep'Filesystem features'|
grep compress,→
$
41
What is a script?
Long commands
Sometimes the command may become really long...
$ while true; do output="$(pgrep -lf zabbix_server)"; if
[ -n "$output" ]; then echo Zabbix server is
running...; fi; sleep 3; done
,→
,→
Zabbix server is running...
Zabbix server is running...
42
Long commandsSo you need to start writing scripts!
43
A shebang
#!/bin/bash
echo "Cleaning /tmp..."
rm -rfv /tmp/*
A shebang is the special character sequence#!at the very beginning of a script
file, followed by thepath to the interpreterthat should be used to execute the
script.
It’s also known as ahashbangorhash-bang, and it allows a script to be run
directly as an executablein Unix-like systems by telling the system which
program (like a shell or Python interpreter) to use.
44
A shebang
#!/bin/bash
echo "Cleaning /tmp..."
rm -rfv /tmp/*
A shebang is the special character sequence#!at the very beginning of a script
file, followed by thepath to the interpreterthat should be used to execute the
script.
It’s also known as ahashbangorhash-bang, and it allows a script to be run
directly as an executablein Unix-like systems by telling the system which
program (like a shell or Python interpreter) to use.
44
A shebang
#!/bin/bash
echo "Cleaning /tmp..."
rm -rfv /tmp/*
A shebang is the special character sequence#!at the very beginning of a script
file, followed by thepath to the interpreterthat should be used to execute the
script.
It’s also known as ahashbangorhash-bang, and it allows a script to be run
directly as an executablein Unix-like systems by telling the system which
program (like a shell or Python interpreter) to use.
44
A bash shebang
echo "Cleaning /tmp..."
rm -rf /tmp/*
$ bash cleanup.sh$ ./cleanup.sh
-bash: ./cleanup.sh: Permission denied
$ chmod +x cleanup.sh$ ./cleanup.sh
Cleaning /tmp...
$
When a script without a shebang is executed directly (e.g.,
./cleanup.sh) and the current shell is Bash, the kernel will attempt to
execute the file using the current shell.
45
A bash shebang
echo "Cleaning /tmp..."
rm -rf /tmp/*
$ bash cleanup.sh$ ./cleanup.sh
-bash: ./cleanup.sh: Permission denied
$ chmod +x cleanup.sh$ ./cleanup.sh
Cleaning /tmp...
$
When a script without a shebang is executed directly (e.g.,
./cleanup.sh) and the current shell is Bash, the kernel will attempt to
execute the file using the current shell.
45
A bash shebang
echo "Cleaning /tmp..."
rm -rf /tmp/*
$ bash cleanup.sh$ ./cleanup.sh
-bash: ./cleanup.sh: Permission denied
$ chmod +x cleanup.sh$ ./cleanup.sh
Cleaning /tmp...
$
When a script without a shebang is executed directly (e.g.,
./cleanup.sh) and the current shell is Bash, the kernel will attempt to
execute the file using the current shell.
45
A bash shebang
echo "Cleaning /tmp..."
rm -rf /tmp/*
$ bash cleanup.sh$ ./cleanup.sh
-bash: ./cleanup.sh: Permission denied
$ chmod +x cleanup.sh$ ./cleanup.sh
Cleaning /tmp...
$
When a script without a shebang is executed directly (e.g.,
./cleanup.sh) and the current shell is Bash, the kernel will attempt to
execute the file using the current shell.
45
A bash shebang
echo "Cleaning /tmp..."
rm -rf /tmp/*
$ bash cleanup.sh$ ./cleanup.sh
-bash: ./cleanup.sh: Permission denied
$ chmod +x cleanup.sh$ ./cleanup.sh
Cleaning /tmp...
$
When a script without a shebang is executed directly (e.g.,
./cleanup.sh) and the current shell is Bash, the kernel will attempt to
execute the file using the current shell.
45
A bash shebang
echo "Cleaning /tmp..."
rm -rf /tmp/*
$ bash cleanup.sh$ ./cleanup.sh
-bash: ./cleanup.sh: Permission denied
$ chmod +x cleanup.sh$ ./cleanup.sh
Cleaning /tmp...
$
When a script without a shebang is executed directly (e.g.,
./cleanup.sh) and the current shell is Bash, the kernel will attempt to
execute the file using the current shell.
45
A bash shebang
Consider a simpleperlscript.
print("I am $ENV{USER}˙");
$ /tmp/echo.pl
-bash: /tmp/echo.pl: Permission denied
$ chmod +x /tmp/echo.pl$ /tmp/echo.pl
/tmp/echo.pl: line 1: syntax error near unexpected token
`"I am $ENV{USER}˙"'
$ perl /tmp/echo.pl
I am vl
46
A bash shebang
Consider a simpleperlscript.
print("I am $ENV{USER}˙");
$ /tmp/echo.pl
-bash: /tmp/echo.pl: Permission denied
$ chmod +x /tmp/echo.pl$ /tmp/echo.pl
/tmp/echo.pl: line 1: syntax error near unexpected token
`"I am $ENV{USER}˙"'
$ perl /tmp/echo.pl
I am vl
46
A bash shebang
Consider a simpleperlscript.
print("I am $ENV{USER}˙");
$ /tmp/echo.pl
-bash: /tmp/echo.pl: Permission denied
$ chmod +x /tmp/echo.pl$ /tmp/echo.pl
/tmp/echo.pl: line 1: syntax error near unexpected token
`"I am $ENV{USER}˙"'
$ perl /tmp/echo.pl
I am vl
46
A bash shebang
Consider a simpleperlscript.
print("I am $ENV{USER}˙");
$ /tmp/echo.pl
-bash: /tmp/echo.pl: Permission denied
$ chmod +x /tmp/echo.pl$ /tmp/echo.pl
/tmp/echo.pl: line 1: syntax error near unexpected token
`"I am $ENV{USER}˙"'
$ perl /tmp/echo.pl
I am vl
46
A bash shebang
Consider a simpleperlscript.
print("I am $ENV{USER}˙");
$ /tmp/echo.pl
-bash: /tmp/echo.pl: Permission denied
$ chmod +x /tmp/echo.pl$ /tmp/echo.pl
/tmp/echo.pl: line 1: syntax error near unexpected token
`"I am $ENV{USER}˙"'
$ perl /tmp/echo.pl
I am vl
46
A shebang
Bash scripts commonly start with#!/bin/bash
On many systems (Linux, macOS, BSDs, NixOS, embedded systems, custom
setups), bash might be installed elsewhere (e.g. /usr/local/bin/bash,
/opt/homebrew/bin/bash). If bash isn’t at /bin/bash, your script won’t run.
Start you bash code with:
#!/usr/bin/env bash
•On almost all modern Unix-like systems (Linux, macOS, BSD, etc.), env
is indeed located at /usr/bin/env
•That’s why it became thede facto portable wayof locating interpreters
(e.g. bash, python3, perl)
•The POSIX standard requires env, but it does not require it to live in
/usr/bin — only that it be somewhere in the user’s $PATH
47
A shebang
Bash scripts commonly start with#!/bin/bash
On many systems (Linux, macOS, BSDs, NixOS, embedded systems, custom
setups), bash might be installed elsewhere (e.g. /usr/local/bin/bash,
/opt/homebrew/bin/bash). If bash isn’t at /bin/bash, your script won’t run.
Start you bash code with:
#!/usr/bin/env bash
•On almost all modern Unix-like systems (Linux, macOS, BSD, etc.), env
is indeed located at /usr/bin/env
•That’s why it became thede facto portable wayof locating interpreters
(e.g. bash, python3, perl)
•The POSIX standard requires env, but it does not require it to live in
/usr/bin — only that it be somewhere in the user’s $PATH
47
A shebang
Bash scripts commonly start with#!/bin/bash
On many systems (Linux, macOS, BSDs, NixOS, embedded systems, custom
setups), bash might be installed elsewhere (e.g. /usr/local/bin/bash,
/opt/homebrew/bin/bash). If bash isn’t at /bin/bash, your script won’t run.
Start you bash code with:
#!/usr/bin/env bash
•On almost all modern Unix-like systems (Linux, macOS, BSD, etc.), env
is indeed located at /usr/bin/env
•That’s why it became thede facto portable wayof locating interpreters
(e.g. bash, python3, perl)
•The POSIX standard requires env, but it does not require it to live in
/usr/bin — only that it be somewhere in the user’s $PATH
47
A shebang
Bash scripts commonly start with#!/bin/bash
On many systems (Linux, macOS, BSDs, NixOS, embedded systems, custom
setups), bash might be installed elsewhere (e.g. /usr/local/bin/bash,
/opt/homebrew/bin/bash). If bash isn’t at /bin/bash, your script won’t run.
Start you bash code with:
#!/usr/bin/env bash
•On almost all modern Unix-like systems (Linux, macOS, BSD, etc.), env
is indeed located at /usr/bin/env
•That’s why it became thede facto portable wayof locating interpreters
(e.g. bash, python3, perl)
•The POSIX standard requires env, but it does not require it to live in
/usr/bin — only that it be somewhere in the user’s $PATH
47
Reading command-line arguments
#!/usr/bin/env bash
if [$1 == ""]; then
# ./backup.sh /etc/resolv.conf
if [ /etc/resolv.conf == "" ]; then
# ./backup.sh
if [== ""]; then
./backup.sh: line 4: [: =: unary operator expected
Variant What it does Safe?
[ -z $1 ] Works, but may break with special characters.✗
[ -z "$1" ]Correct, safe way to check for an empty argument.✓
49
Reading command-line arguments
#!/usr/bin/env bash
if [$1 == ""]; then
# ./backup.sh /etc/resolv.conf
if [ /etc/resolv.conf == "" ]; then
# ./backup.sh
if [== ""]; then
./backup.sh: line 4: [: =: unary operator expected
Variant What it does Safe?
[ -z $1 ] Works, but may break with special characters.✗
[ -z "$1" ]Correct, safe way to check for an empty argument.✓
49
Reading command-line arguments
#!/usr/bin/env bash
if [$1 == ""]; then
# ./backup.sh /etc/resolv.conf
if [ /etc/resolv.conf == "" ]; then
# ./backup.sh
if [== ""]; then
./backup.sh: line 4: [: =: unary operator expected
Variant What it does Safe?
[ -z $1 ] Works, but may break with special characters.✗
[ -z "$1" ]Correct, safe way to check for an empty argument.✓
49
Reading command-line arguments
#!/usr/bin/env bash
if [$1 == ""]; then
# ./backup.sh /etc/resolv.conf
if [ /etc/resolv.conf == "" ]; then
# ./backup.sh
if [== ""]; then
./backup.sh: line 4: [: =: unary operator expected
Variant What it does Safe?
[ -z $1 ] Works, but may break with special characters.✗
[ -z "$1" ]Correct, safe way to check for an empty argument.✓
49
Reading command-line arguments
#!/usr/bin/env bash
if [$1 == ""]; then
# ./backup.sh /etc/resolv.conf
if [ /etc/resolv.conf == "" ]; then
# ./backup.sh
if [== ""]; then
./backup.sh: line 4: [: =: unary operator expected
Variant What it does Safe?
[ -z $1 ] Works, but may break with special characters.✗
[ -z "$1" ]Correct, safe way to check for an empty argument.✓
49
Reading command-line arguments
#!/usr/bin/env bash
if [ -z "$1" ]; then
echo "Usage:$0<file> [backup directory]"
echo "default backup directory - $HOME/backup"
exit 1
fi
FILE="$1"BACKUP_DIR="$2"
if [ -z "$BACKUP_DIR" ]; then
# default backup directory
BACKUP_DIR="$HOME/backup"
fi
# create backup directory if it doesn’t exist
mkdir-p"$BACKUP_DIR"
cp "$FILE" "$BACKUP_DIR/"
echo "Backup of ’$FILE’ saved to ’$BACKUP_DIR/’"
50
Reading command-line arguments
#!/usr/bin/env bash
if [ -z "$1" ]; then
echo "Usage:$0<file> [backup directory]"
echo "default backup directory - $HOME/backup"
exit 1
fi
FILE="$1"BACKUP_DIR="$2"
if [ -z "$BACKUP_DIR" ]; then
# default backup directory
BACKUP_DIR="$HOME/backup"
fi
# create backup directory if it doesn’t exist
mkdir-p"$BACKUP_DIR"
cp "$FILE" "$BACKUP_DIR/"
echo "Backup of ’$FILE’ saved to ’$BACKUP_DIR/’"
50
Reading command-line arguments
#!/usr/bin/env bash
if [ -z "$1" ]; then
echo "Usage:$0<file> [backup directory]"
echo "default backup directory - $HOME/backup"
exit 1
fi
FILE="$1"BACKUP_DIR="$2"
if [ -z "$BACKUP_DIR" ]; then
# default backup directory
BACKUP_DIR="$HOME/backup"
fi
# create backup directory if it doesn’t exist
mkdir-p"$BACKUP_DIR"
cp "$FILE" "$BACKUP_DIR/"
echo "Backup of ’$FILE’ saved to ’$BACKUP_DIR/’"
50
Reading command-line arguments
#!/usr/bin/env bash
if [ -z "$1" ]; then
echo "Usage:$0<file> [backup directory]"
echo "default backup directory - $HOME/backup"
exit 1
fi
FILE="$1"BACKUP_DIR="$2"
if [ -z "$BACKUP_DIR" ]; then
# default backup directory
BACKUP_DIR="$HOME/backup"
fi
# create backup directory if it doesn’t exist
mkdir-p"$BACKUP_DIR"
cp "$FILE" "$BACKUP_DIR/"
echo "Backup of ’$FILE’ saved to ’$BACKUP_DIR/’"
50
Reading command-line arguments
#!/usr/bin/env bash
if [ -z "$1" ]; then
echo "Usage:$0<file> [backup directory]"
echo "default backup directory - $HOME/backup"
exit 1
fi
FILE="$1"BACKUP_DIR="$2"
if [ -z "$BACKUP_DIR" ]; then
# default backup directory
BACKUP_DIR="$HOME/backup"
fi
# create backup directory if it doesn’t exist
mkdir-p"$BACKUP_DIR"
cp "$FILE" "$BACKUP_DIR/"
echo "Backup of ’$FILE’ saved to ’$BACKUP_DIR/’"
50
Reading command-line arguments
#!/usr/bin/env bash
if [ -z "$1" ]; then
echo "Usage:$0<file> [backup directory]"
echo "default backup directory - $HOME/backup"
exit 1
fi
FILE="$1"BACKUP_DIR="$2"
if [ -z "$BACKUP_DIR" ]; then
# default backup directory
BACKUP_DIR="$HOME/backup"
fi
# create backup directory if it doesn’t exist
mkdir-p"$BACKUP_DIR"
cp "$FILE" "$BACKUP_DIR/"
echo "Backup of ’$FILE’ saved to ’$BACKUP_DIR/’"
50
Reading command-line arguments
#!/usr/bin/env bash
if [ -z "$1" ]; then
echo "Usage:$0<file> [backup directory]"
echo "default backup directory - $HOME/backup"
exit 1
fi
FILE="$1"BACKUP_DIR="$2"
if [ -z "$BACKUP_DIR" ]; then
# default backup directory
BACKUP_DIR="$HOME/backup"
fi
# create backup directory if it doesn’t exist
mkdir-p"$BACKUP_DIR"
cp "$FILE" "$BACKUP_DIR/"
echo "Backup of ’$FILE’ saved to ’$BACKUP_DIR/’"
50
Reading command-line arguments
#!/usr/bin/env bash
if [ -z "$1" ]; then
echo "Usage:$0<file> [backup directory]"
echo "default backup directory - $HOME/backup"
exit 1
fi
FILE="$1"BACKUP_DIR="$2"
if [ -z "$BACKUP_DIR" ]; then
# default backup directory
BACKUP_DIR="$HOME/backup"
fi
# create backup directory if it doesn’t exist
mkdir-p"$BACKUP_DIR"
cp "$FILE" "$BACKUP_DIR/"
echo "Backup of ’$FILE’ saved to ’$BACKUP_DIR/’"
50
Reading command-line arguments
#!/usr/bin/env bash
if [ -z "$1" ]; then
echo "Usage:$0<file> [backup directory]"
echo "default backup directory - $HOME/backup"
exit 1
fi
FILE="$1"BACKUP_DIR="$2"
if [ -z "$BACKUP_DIR" ]; then
# default backup directory
BACKUP_DIR="$HOME/backup"
fi
# create backup directory if it doesn’t exist
mkdir-p"$BACKUP_DIR"
cp "$FILE" "$BACKUP_DIR/"
echo "Backup of ’$FILE’ saved to ’$BACKUP_DIR/’"
50
Error handling
$ ./backup.sh non-existent.txt
cp: cannot stat'non-existent.txt': No such file or directory
Backup of ’non-existent.txt’ saved to ’/home/vl/backup/’
cp "$FILE" "$BACKUP_DIR/"
if [ $? -ne 0 ]; then
echo "An error occured, see above."
exit 1
fi
cp: cannot stat'non-existent.txt': No such file or
directory,→
An error occured, see above.
if ! cp "$FILE" "$BACKUP_DIR/"; then
exit 1
fi
cp: cannot stat'non-existent.txt': No such file or
directory,→
52
Error handling
$ ./backup.sh non-existent.txt
cp: cannot stat'non-existent.txt': No such file or directory
Backup of ’non-existent.txt’ saved to ’/home/vl/backup/’
cp "$FILE" "$BACKUP_DIR/"
if [ $? -ne 0 ]; then
echo "An error occured, see above."
exit 1
fi
cp: cannot stat'non-existent.txt': No such file or
directory,→
An error occured, see above.
if ! cp "$FILE" "$BACKUP_DIR/"; then
exit 1
fi
cp: cannot stat'non-existent.txt': No such file or
directory,→
52
Error handling
$ ./backup.sh non-existent.txt
cp: cannot stat'non-existent.txt': No such file or directory
Backup of ’non-existent.txt’ saved to ’/home/vl/backup/’
cp "$FILE" "$BACKUP_DIR/"
if [ $? -ne 0 ]; then
echo "An error occured, see above."
exit 1
fi
cp: cannot stat'non-existent.txt': No such file or
directory,→
An error occured, see above.
if ! cp "$FILE" "$BACKUP_DIR/"; then
exit 1
fi
cp: cannot stat'non-existent.txt': No such file or
directory,→
52
Error handling
$ ./backup.sh non-existent.txt
cp: cannot stat'non-existent.txt': No such file or directory
Backup of ’non-existent.txt’ saved to ’/home/vl/backup/’
cp "$FILE" "$BACKUP_DIR/"
if [ $? -ne 0 ]; then
echo "An error occured, see above."
exit 1
fi
cp: cannot stat'non-existent.txt': No such file or
directory,→
An error occured, see above.
if ! cp "$FILE" "$BACKUP_DIR/"; then
exit 1
fi
cp: cannot stat'non-existent.txt': No such file or
directory,→
52
Error handling
$ ./backup.sh non-existent.txt
cp: cannot stat'non-existent.txt': No such file or directory
Backup of ’non-existent.txt’ saved to ’/home/vl/backup/’
cp "$FILE" "$BACKUP_DIR/"
if [ $? -ne 0 ]; then
echo "An error occured, see above."
exit 1
fi
cp: cannot stat'non-existent.txt': No such file or
directory,→
An error occured, see above.
if ! cp "$FILE" "$BACKUP_DIR/"; then
exit 1
fi
cp: cannot stat'non-existent.txt': No such file or
directory,→
52
Error handling
if ! mkdir -p "$BACKUP_DIR/"; then
exit 1
fi
if ! cp "$FILE" "$BACKUP_DIR/"; then
exit 1
fi
if ! ls "$BACKUP_DIR/$(basename $FILE)" > /dev/null;
then,→
exit 1
fi
mkdir -p "$BACKUP_DIR/" || exit 1
cp "$FILE" "$BACKUP_DIR/" || exit 1
ls "$BACKUP_DIR/$(basename FILE)" > /dev/null || exit 1
53
Error handling
if ! mkdir -p "$BACKUP_DIR/"; then
exit 1
fi
if ! cp "$FILE" "$BACKUP_DIR/"; then
exit 1
fi
if ! ls "$BACKUP_DIR/$(basename $FILE)" > /dev/null;
then,→
exit 1
fi
mkdir -p "$BACKUP_DIR/" || exit 1
cp "$FILE" "$BACKUP_DIR/" || exit 1
ls "$BACKUP_DIR/$(basename FILE)" > /dev/null || exit 1
53
Error handling
#!/usr/bin/env bash
set -e
false
echo "continue with the script"
$ ./test.sh
continue with the script
#!/usr/bin/env bash
set -e
set -o pipefail
false | true
echo "continue with the script"
$ ./test.sh
$ echo $?
1
55
Error handling
#!/usr/bin/env bash
set -e
false
echo "continue with the script"
$ ./test.sh
continue with the script
#!/usr/bin/env bash
set -e
set -o pipefail
false | true
echo "continue with the script"
$ ./test.sh
$ echo $?
1
55
Error handling
#!/usr/bin/env bash
set -e
false
echo "continue with the script"
$ ./test.sh
continue with the script
#!/usr/bin/env bash
set -e
set -o pipefail
false | true
echo "continue with the script"
$ ./test.sh
$ echo $?
1
55
Error handling
#!/usr/bin/env bash
set -e
false
echo "continue with the script"
$ ./test.sh
continue with the script
#!/usr/bin/env bash
set -e
set -o pipefail
false | true
echo "continue with the script"
$ ./test.sh
$ echo $?
1
55
Debugging
$ ./backup.sh backup.sh "/opt/backup dir"
./backup.sh: line 12: [: /opt/backup: binary operator
expected,→
12: if [ -z $BACKUP_DIR ]; then
13: BACKUP_DIR="$HOME/backup"
14: fi
set -x
if [ -z $BACKUP_DIR ]; then
BACKUP_DIR="$HOME/backup"
fi
set +x
$ ./backup.sh backup.sh "/opt/backup dir"
+'['-z /opt/backup dir']'
./backup.sh: line 12: [: /opt/backup: binary operator expected
+ set +x
56
Debugging
$ ./backup.sh backup.sh "/opt/backup dir"
./backup.sh: line 12: [: /opt/backup: binary operator
expected,→
12: if [ -z $BACKUP_DIR ]; then
13: BACKUP_DIR="$HOME/backup"
14: fi
set -x
if [ -z $BACKUP_DIR ]; then
BACKUP_DIR="$HOME/backup"
fi
set +x
$ ./backup.sh backup.sh "/opt/backup dir"
+'['-z /opt/backup dir']'
./backup.sh: line 12: [: /opt/backup: binary operator expected
+ set +x
56
Debugging
$ ./backup.sh backup.sh "/opt/backup dir"
./backup.sh: line 12: [: /opt/backup: binary operator
expected,→
12: if [ -z $BACKUP_DIR ]; then
13: BACKUP_DIR="$HOME/backup"
14: fi
set -x
if [ -z $BACKUP_DIR ]; then
BACKUP_DIR="$HOME/backup"
fi
set +x
$ ./backup.sh backup.sh "/opt/backup dir"
+'['-z /opt/backup dir']'
./backup.sh: line 12: [: /opt/backup: binary operator expected
+ set +x
56
Debugging
$ ./backup.sh backup.sh "/opt/backup dir"
./backup.sh: line 12: [: /opt/backup: binary operator
expected,→
12: if [ -z $BACKUP_DIR ]; then
13: BACKUP_DIR="$HOME/backup"
14: fi
set -x
if [ -z $BACKUP_DIR ]; then
BACKUP_DIR="$HOME/backup"
fi
set +x
$ ./backup.sh backup.sh "/opt/backup dir"
+'['-z /opt/backup dir']'
./backup.sh: line 12: [: /opt/backup: binary operator expected
+ set +x
56
Built-in string operations
If you use bash 4 or later, don’t bother with ’tr’ and ’expr’:
$ str=Shell; echo $str | tr [a-z] [A-Z]
SHELL
Use bash built-in string operations power:
str=shell; echo ${str^}; echo ${str^^}; echo ${str„}
Shell
SHELL
shell
59
Built-in string operations
If you use bash 4 or later, don’t bother with ’tr’ and ’expr’:
$ str=Shell; echo $str | tr [a-z] [A-Z]
SHELL
Use bash built-in string operations power:
str=shell; echo ${str^}; echo ${str^^}; echo ${str„}
Shell
SHELL
shell
59
Built-in string operations
${variable#pattern}
Removes the shortest match of pattern from the beginning.
${variable##pattern}
Removes the longest match of pattern from the beginning.
${variable%pattern}
Removes the shortest match of pattern from the end.
${variable%%pattern}
Removes the longest match of pattern from the end.
Example:
filename="report.2025.txt"
echo "${filename%.*}" # Output: report.2025
echo "${filename##*.}" # Output: txt
60
Built-in string operations
${variable#pattern}
Removes the shortest match of pattern from the beginning.
${variable##pattern}
Removes the longest match of pattern from the beginning.
${variable%pattern}
Removes the shortest match of pattern from the end.
${variable%%pattern}
Removes the longest match of pattern from the end.
Example:
filename="report.2025.txt"
echo "${filename%.*}" # Output: report.2025
echo "${filename##*.}" # Output: txt
60
Brace expansion
Brace expansion in Bash is a feature thatgenerates strings from patterns
without loops or external commands.
Ranges:
$ echo file{1..3}.txt
file1.txt file2.txt file3.txt
Lists:
$ echo {A,B,C}
A B C
$ rm -fv server.c.{orig,rej,bak}
# translates to -> rm -fv server.c.orig server.c.rej server.c.bak
removed'server.c.bak'
61
Brace expansion
Brace expansion in Bash is a feature thatgenerates strings from patterns
without loops or external commands.
Ranges:
$ echo file{1..3}.txt
file1.txt file2.txt file3.txt
Lists:
$ echo {A,B,C}
A B C
$ rm -fv server.c.{orig,rej,bak}
# translates to -> rm -fv server.c.orig server.c.rej server.c.bak
removed'server.c.bak'
61
Brace expansion
Brace expansion in Bash is a feature thatgenerates strings from patterns
without loops or external commands.
Ranges:
$ echo file{1..3}.txt
file1.txt file2.txt file3.txt
Lists:
$ echo {A,B,C}
A B C
$ rm -fv server.c.{orig,rej,bak}
# translates to -> rm -fv server.c.orig server.c.rej server.c.bak
removed'server.c.bak'
61
Brace expansion
Brace expansion in Bash is a feature thatgenerates strings from patterns
without loops or external commands.
Ranges:
$ echo file{1..3}.txt
file1.txt file2.txt file3.txt
Lists:
$ echo {A,B,C}
A B C
$ rm -fv server.c.{orig,rej,bak}
# translates to -> rm -fv server.c.orig server.c.rej server.c.bak
removed'server.c.bak'
61
Some more tricks?
Randomize
$ echo $[RANDOM]
11419
$ [ $[RANDOM % 2] -eq 0 ] && echo -n Gleb || echo -n dimir; echo will go
to India'!',→
dimir will go to India!
$ sleep $(( RANDOM % 5 + 1 )) # sleep for 1–5 secondsThis is called basharithmetic evaluation.
•(( ))evaluates arithmetic expressions
•$(( ))expands to the numeric result
•Works with standard arithmetic operators(+, -, *, /, %, ++, --, etc.)
•No need for$before variable names inside(( ))
62
Randomize
$ echo $[RANDOM]
11419
$ [ $[RANDOM % 2] -eq 0 ] && echo -n Gleb || echo -n dimir; echo will go
to India'!',→
dimir will go to India!
$ sleep $(( RANDOM % 5 + 1 )) # sleep for 1–5 secondsThis is called basharithmetic evaluation.
•(( ))evaluates arithmetic expressions
•$(( ))expands to the numeric result
•Works with standard arithmetic operators(+, -, *, /, %, ++, --, etc.)
•No need for$before variable names inside(( ))
62
Randomize
$ echo $[RANDOM]
11419
$ [ $[RANDOM % 2] -eq 0 ] && echo -n Gleb || echo -n dimir; echo will go
to India'!',→
dimir will go to India!
$ sleep $(( RANDOM % 5 + 1 )) # sleep for 1–5 secondsThis is called basharithmetic evaluation.
•(( ))evaluates arithmetic expressions
•$(( ))expands to the numeric result
•Works with standard arithmetic operators(+, -, *, /, %, ++, --, etc.)
•No need for$before variable names inside(( ))
62
Randomize
$ echo $[RANDOM]
11419
$ [ $[RANDOM % 2] -eq 0 ] && echo -n Gleb || echo -n dimir; echo will go
to India'!',→
dimir will go to India!
$ sleep $(( RANDOM % 5 + 1 )) # sleep for 1–5 secondsThis is called basharithmetic evaluation.
•(( ))evaluates arithmetic expressions
•$(( ))expands to the numeric result
•Works with standard arithmetic operators(+, -, *, /, %, ++, --, etc.)
•No need for$before variable names inside(( ))
62
Wildcard expansion
$ ls * | grep bashrc
$ ls .* | grep bashrc
.bashrc
Make sure you never delete hidden files like this:
$ rm -rf .*
because ".*" matches ".." (higher-level directory)!
$ ls -R .* | grep bashrc
bash.bashrc
bash.bashrc
bash.bashrc
bash.bashrc
Correct way of doing this:
$ rm -rfv .[a-zA-Z]*
64
Wildcard expansion
$ ls * | grep bashrc
$ ls .* | grep bashrc
.bashrc
Make sure you never delete hidden files like this:
$ rm -rf .*
because ".*" matches ".." (higher-level directory)!
$ ls -R .* | grep bashrc
bash.bashrc
bash.bashrc
bash.bashrc
bash.bashrc
Correct way of doing this:
$ rm -rfv .[a-zA-Z]*
64
Wildcard expansion
$ ls * | grep bashrc
$ ls .* | grep bashrc
.bashrc
Make sure you never delete hidden files like this:
$ rm -rf .*
because ".*" matches ".." (higher-level directory)!
$ ls -R .* | grep bashrc
bash.bashrc
bash.bashrc
bash.bashrc
bash.bashrc
Correct way of doing this:
$ rm -rfv .[a-zA-Z]*
64
Following the log file
Log file rotated by logrotate.
$ tail -f /var/log/zabbix_server.log
29631:20160927:152455.721 In substitute_functions()
29631:20160927:152455.721 In zbx_extract_functionids()
tr_num:1,→
tail: /tmp/foo.log: file truncated
$ tail
29631:20160927:152455.721 In substitute_functions()
29631:20160927:152455.721 In zbx_extract_functionids() tr_num:1
tail: /tmp/foo.log: file truncated
29631:20160927:152455.721 End of zbx_extract_functionids() functionids_num:1
29631:20160927:152455.721 In zbx_populate_function_items() functionids_num:1
29631:20160927:152455.721 End of zbx_populate_function_items() ifuncs_num:1
29631:20160927:152455.721 In zbx_evaluate_item_functions() ifuncs_num:1
29631:20160927:152455.721 In evaluate_function() function:'Zabbix server:test.strlen()'
29631:20160927:152455.721 In evaluate_STRLEN()
29631:20160927:152455.721 In evaluate_LAST()
65
Following the log file
Log file rotated by logrotate.
$ tail -f /var/log/zabbix_server.log
29631:20160927:152455.721 In substitute_functions()
29631:20160927:152455.721 In zbx_extract_functionids()
tr_num:1,→
tail: /tmp/foo.log: file truncated
$ tail
29631:20160927:152455.721 In substitute_functions()
29631:20160927:152455.721 In zbx_extract_functionids() tr_num:1
tail: /tmp/foo.log: file truncated
29631:20160927:152455.721 End of zbx_extract_functionids() functionids_num:1
29631:20160927:152455.721 In zbx_populate_function_items() functionids_num:1
29631:20160927:152455.721 End of zbx_populate_function_items() ifuncs_num:1
29631:20160927:152455.721 In zbx_evaluate_item_functions() ifuncs_num:1
29631:20160927:152455.721 In evaluate_function() function:'Zabbix server:test.strlen()'
29631:20160927:152455.721 In evaluate_STRLEN()
29631:20160927:152455.721 In evaluate_LAST()
65
History expansion
The History library provides a history expansion feature that is similar to the
history expansion provided by csh. It is used tomanipulate the history
information. The following areevent designators. It is a reference to a
command line entry in the history list
!^ first argument
!$ last argument
!* all arguments
!:2 second argument
!:2-3 second to third arguments
!:2-$ second to last arguments
!:2* second to last arguments
!:2- second to next to last arguments
!:0 the command itself
!! repeat the previous line
66
Working with processes
$ ps ax | grep zabbix_proxy
28559 ? S 0:00 sbin/zabbix_proxy
28560 ? S 0:00 sbin/zabbix_proxy
$
28559
28560
$ pgrep
28559 sbin/zabbix_proxy -c /etc/zabbix/zabbix_proxy.conf
28560 sbin/zabbix_proxy: configuration syncer [syncing configuration]
-l, --list-name
List the process name as well as the process ID (pgrep only)
-a, --list-full
List the full command line as well as the process ID (pgrep only)
74
Working with processes
$ ps ax | grep zabbix_proxy
28559 ? S 0:00 sbin/zabbix_proxy
28560 ? S 0:00 sbin/zabbix_proxy
$
28559
28560
$ pgrep
28559 sbin/zabbix_proxy -c /etc/zabbix/zabbix_proxy.conf
28560 sbin/zabbix_proxy: configuration syncer [syncing configuration]
-l, --list-name
List the process name as well as the process ID (pgrep only)
-a, --list-full
List the full command line as well as the process ID (pgrep only)
74
Working with processes
$ ps ax | grep zabbix_proxy
28559 ? S 0:00 sbin/zabbix_proxy
28560 ? S 0:00 sbin/zabbix_proxy
$
28559
28560
$ pgrep
28559 sbin/zabbix_proxy -c /etc/zabbix/zabbix_proxy.conf
28560 sbin/zabbix_proxy: configuration syncer [syncing configuration]
-l, --list-name
List the process name as well as the process ID (pgrep only)
-a, --list-full
List the full command line as well as the process ID (pgrep only)
74
Working with processes
$ pgrep -lfa poller
28564 sbin/zabbix_proxy: browser poller
28573 sbin/zabbix_proxy: agent poller
28575 sbin/zabbix_proxy: snmp poller
-f, --full
The pattern is matched against the full command line
$ pkill -e zabbix_proxy
zabbix_proxy killed (pid 31152)
zabbix_proxy killed (pid 31153)
-e, --echo
Display name and PID of the process being killed (pkill only)
$ pkill -fe poller
zabbix_proxy killed (pid 31656)
zabbix_proxy killed (pid 31661)
75
Working with processes
$ pgrep -lfa poller
28564 sbin/zabbix_proxy: browser poller
28573 sbin/zabbix_proxy: agent poller
28575 sbin/zabbix_proxy: snmp poller
-f, --full
The pattern is matched against the full command line
$ pkill -e zabbix_proxy
zabbix_proxy killed (pid 31152)
zabbix_proxy killed (pid 31153)
-e, --echo
Display name and PID of the process being killed (pkill only)
$ pkill -fe poller
zabbix_proxy killed (pid 31656)
zabbix_proxy killed (pid 31661)
75
Working with processes
$ pgrep -lfa poller
28564 sbin/zabbix_proxy: browser poller
28573 sbin/zabbix_proxy: agent poller
28575 sbin/zabbix_proxy: snmp poller
-f, --full
The pattern is matched against the full command line
$ pkill -e zabbix_proxy
zabbix_proxy killed (pid 31152)
zabbix_proxy killed (pid 31153)
-e, --echo
Display name and PID of the process being killed (pkill only)
$ pkill -fe poller
zabbix_proxy killed (pid 31656)
zabbix_proxy killed (pid 31661)
75
Working with processes
$ pgrep -lfa poller
28564 sbin/zabbix_proxy: browser poller
28573 sbin/zabbix_proxy: agent poller
28575 sbin/zabbix_proxy: snmp poller
-f, --full
The pattern is matched against the full command line
$ pkill -e zabbix_proxy
zabbix_proxy killed (pid 31152)
zabbix_proxy killed (pid 31153)
-e, --echo
Display name and PID of the process being killed (pkill only)
$ pkill -fe poller
zabbix_proxy killed (pid 31656)
zabbix_proxy killed (pid 31661)
75