Bash_commands
Bash Commands Memo
Introduction
KISS principle
When using Linux, one problem that may easily be ignored by greenhands is: Why Linux. For programmers, Linux has great advantages over Windows OS for its light, free and open-source characteristics. If you use Linux the same way you use Windows, you won’t be able to harness the spirit and greatest strengths of Linux.
Therefore, for every Linux beginner, it is very important to familiarize themselves with Linux/Unix philosophy and practice it in their usage! I recommend this Blog[1] (author: Yifeng Ruan) which clearly explains the philosophy of Unix.
In this Blog, it says:
The Wikipedia page lists several versions of the Unix philosophy, with different people offering their own summaries. Doug McIlroy, the inventor of the pipe command, summarized it in three principles, while Eric S. Raymond, in his book The Art of Unix Programming, expanded it to a total of 17 principles (in both the English and Chinese editions).
However, I noticed that everyone agrees on one fundamental principle of the Unix philosophy: the “Principle of Simplicity“—solving problems in the simplest way possible. This is also known as the famous KISS principle (Keep It Simple, Stupid), which means “keep things simple and straightforward.”
Specifically, what is the Principle of Simplicity? From my perspective, the Principle of Simplicity means refining every operation to its utmost simplicity, focusing solely on accomplishing a single, independent small task, and then efficiently combining these tasks to achieve more complex objectives.
For example, using pipes|
to connect commands enables us to use several small commands and connect them together so as to finish customed and complex tasks. (If you don’t know what pipe is, you can go through Missing semester for Lec1 first.) In contrast, commands in powershell don’t seem to follow the Principle of Simplicity in some circumstances.
- IF you want to list all the processes named “Notepad” and stop them:
In Bash:
1 |
|
In PowerShell:
1 |
|
- IF you want to count total lines in all
.log
files recursively:
In Bash:
1 |
|
In PowerShell:
1 |
|
- IF you want to list all files in a directory with size and last modified time:
In Bash:
1 |
|
In PowerShell:
1 |
|
PowerShell is object-oriented, meaning it treats command outputs as objects with properties and methods, allowing for more complex and manipulations directly within the shell, though it may require more verbose code to access and manipulate these properties. In contrast, Bash is text-based, handling command outputs as plain text streams, which are then processed using text utilities like
awk
andsed
for parsing and transformation. While Bash’s text-based approach can be simpler for straightforward tasks, PowerShell’s object-oriented nature provides richer functionality and easier handling of structured data, albeit with potentially increased complexity in scripting.
How to learn Bash commands
Thus, it’s of great importance to follow KISS rules while learning thousands of Bash commands. All commands are used for efficiency and all commands must remain simple and “stupid” independently.
In the following articles, I will continuously update my journey of learning Bash commands and share concise study notes for your reference. Several basic commands and commands that have few options like ls
and logout
won’t be listed into the updating plan. This Blog only focuses on those commands that are simple but powerful.
Recommended Tools
I strongly recommend tldr[2] for learning Bash commands in a simple way instead of searching for horribly long man
files tutorial.
You can go to the https://tldr.sh/ for searching. You can also install tldr locally in your Linux systems but it will be a little bit slow.
Remember, keep it simple, stupid.
Commands
Table of contents
Text processing:
grep | search for specific patterns within files or input text |
---|---|
grep
command
grep
is a powerful command-line tool in Unix/Linux used to search for specific patterns within files or input text.
1 |
|
pattern
: The text or regular expression to search for.file
: The file(s) to search within. If omitted,grep
reads from standard input.
For example, you can using the grep
command by using pipes.
1 |
|
This command will first output the file contents of sshd_config
while the content itself won’t be printed directly into the screen. It will be transmitted as the input of the grep command.
Common Options
-i
: Ignore case (case-insensitive search).
1 |
|
-v
: Invert match (show lines that do not match the pattern).
1 |
|
-r
or-R
: Recursively search directories.
1 |
|
-n
: Show line numbers of matching lines.
1 |
|
-c
: Count the number of matching lines.
1 |
|
-l
: List filenames containing the pattern.
1 |
|
-w
: Match whole words only.
1 |
|
-A
,-B
,-C
: Show lines after, before, or around the match.
1 |
|
For example, I have a directory (current) and exists files as below:
1 |
|
Now I can use several commands as below to efficiently search specific information that I want!
I can use -r
to search for the whole current directory.
1 |
|
1 |
|
1 |
|
1 |
|
1 |
|
1 |
|
1 |
|
1 |
|
1 |
|
1 |
|
You can make the command line more complex to get more specific data!
1 |
|
1 |
|
More specific:
1 |
|
Using the -h
options to forbid grep showing filenames while searching the directory recursively. Adding more pipes and using Regex can enable developers to make more specific pattern matching problems more freely.
1 |
|
By using this command, you can get all the mottos for all person’s files, which will significantly enhance one’s working efficiency. For more options, you can typing man grep
for advanced usage.
awk
command
AWK is a powerful text-processing language designed for pattern scanning and processing. AWK is particularly useful for manipulating structured data, such as log files, CSV files, or any text files with consistent formatting. It operates on a line-by-line basis.
AWK is named after its creators—Alfred Aho, Peter Weinberger, and Brian Kernighan.
AWK is a powerful command. It can also be seen as a programming language! An AWK program consists of a series of patterns and actions. The general syntax is:
1 |
|
- Pattern: Specifies when the action should be executed (e.g., matching a specific line or condition).
- Action: Defines what to do when the pattern matches (e.g., print a field, perform a calculation).
If no pattern is provided, the action is applied to every line. If no action is provided, the default action is to print the entire line. By default, AWK splits each line into fields based on whitespace (spaces or tabs). Fields are accessed using $1
, $2
, $3
, etc., where $1
is the first field, $2
is the second, and so on. The entire line is stored in $0
.
Common Options
Printing Specific Fields
Filtering Lines Based on a Condition
Using Built-in Variables
Changing the Field Separator
Using BEGIN and END Blocks
Using Regular Expression
Conditional Statements
Associative Arrays
String Manipulation
Custom Functions
Output Redirection
Assuming I have a file like below:
1 |
|
- Printing Specific Fields
1 |
|
- Filtering Lines Based on a Condition
1 |
|
The basic logic for AWK is if-else statement, it first scans the text and used the judgements for if $3 > 25, then print $0
- Using Built-in Variables
AWK provides several built-in variables:
NR
: Current line number.NF
: Number of fields in the current line.FS
: Field separator (default is whitespace).OFS
: Output field separator (default is space).
1 |
|
- Changing the Field Separator
Use the FS
variable to specify a custom field separator, such as a comma for CSV files.
Example: Print the second field from a CSV file.
1 |
|
Input (data.csv
):
1 |
|
Output:
1 |
|
- Using BEGIN and END Blocks
The BEGIN
block is executed before processing any input, and the END
block is executed after all input is processed. You can use it as a programming language for complex tasks!
1 |
|
Output:
1 |
|
- Regular Expressions: AWK supports regular expressions for pattern matching. Use
~
to match and!~
to negate a match.
Example: Print lines where the second field contains “Smith”.
1 |
|
- Conditional Statements
AWK supports if-else
statements for more complex logic.
Example: Classify ages as “Young” or “Old”.
1 |
|
- Associative Arrays
AWK supports associative arrays (like dictionaries) for storing and retrieving data.
Example: Count the frequency of each unique value in the third field.
1 |
|
- String Manipulation
AWK provides functions for string manipulation, such as length
, substr
, and toupper
. Like the <string>
toolbox in cpp!
Example: Print the length of the first field.
1 |
|
- Custom Functions
You can define custom functions in AWK for reusable logic.
Example: Define a function to calculate the square of a number.
1 |
|
- Output Redirection
AWK allows you to redirect output to files.
Example: Write the first field to a new file.
1 |
|