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

From Yifeng Ruan's Blog

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
ps aux | grep [n]otepad | awk '{print $2}' | xargs kill

In PowerShell:

1
Get-Process | Where-Object {$_.Name -eq "notepad"} | Stop-Process
  • IF you want to count total lines in all .log files recursively:

In Bash:

1
find . -name "*.log" -exec cat {} + | wc -l  

In PowerShell:

1
Get-ChildItem -Recurse -Filter *.log | ForEach-Object { Get-Content $_ } | Measure-Object -Line | Select-Object -ExpandProperty Lines  
  • IF you want to list all files in a directory with size and last modified time:

In Bash:

1
ls -l --time-style=+"%Y-%m-%d %H:%M:%S"  

In PowerShell:

1
Get-ChildItem | Select-Object Name, Length, LastWriteTime | Format-Table -AutoSize

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 and sed 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.

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
grep [options] pattern [file]
  • 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
cat /etc/ssh/sshd_config | grep Port

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
grep -i "hello" file.txt
  • -v: Invert match (show lines that do not match the pattern).
1
grep -v "error" file.txt
  • -r or -R: Recursively search directories.
1
grep -r "pattern" /path/to/dir
  • -n: Show line numbers of matching lines.
1
grep -n "pattern" file.txt
  • -c: Count the number of matching lines.
1
grep -c "pattern" file.txt
  • -l: List filenames containing the pattern.
1
grep -l "pattern" *.txt
  • -w: Match whole words only.
1
grep -w "word" file.txt
  • -A, -B, -C: Show lines after, before, or around the match.
1
2
3
grep -A 2 "pattern" file.txt  # Show 2 lines after the match
grep -B 2 "pattern" file.txt # Show 2 lines before the match
grep -C 2 "pattern" file.txt # Show 2 lines before and after the match

For example, I have a directory (current) and exists files as below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
.
├── grep_test.txt
└── sub_dirc
├── modified_1.txt
└── modified_2.txt

2 directories, 3 files

cat grep_test.txt
Hello my name is Jack.
I am 18 year's old.
Do you like me?
I want to make friends with you.
Remember my name, my name is JACK!
HAahah
do you know my favourite motto?
Knowledge isn't free, you have to pay attention.

cat ./sub_dirc/modified_1.txt
Hello my name is Henry.
I am 17 year's old.
Do you like me?
I want to make friends with you.
Remember my name, my name is Henry!
HAahah
do you know my favourite motto?
Nothing is possible

❯ cat ./sub_dirc/modified_2.txt
Hello my name is Kate.
I am 20 year's old.
Do you like us?
I want to make friends with you.
Remember my name, my name is KatE!
HAahah
do you know my favourite motto?
Open source is the best thing in the world!

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
grep -r "Hello" ./
1
2
3
./sub_dirc/modified_1.txt:Hello my name is Henry.
./sub_dirc/modified_2.txt:Hello my name is Kate.
./grep_test.txt:Hello my name is Jack.

1
grep -nri "Jack" ./
1
2
./grep_test.txt:1:Hello my name is Jack.
./grep_test.txt:5:Remember my name, my name is JACK!

1
grep -nrc "Hello" ./
1
2
3
./sub_dirc/modified_1.txt:1
./sub_dirc/modified_2.txt:1
./grep_test.txt:1

1
grep -nrv "Hello" ./
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
./sub_dirc/modified_1.txt:2:I am 17 year's old.
./sub_dirc/modified_1.txt:3:Do you like me?
./sub_dirc/modified_1.txt:4:I want to make friends with you.
./sub_dirc/modified_1.txt:5:Remember my name, my name is Henry!
./sub_dirc/modified_1.txt:6:HAahah
./sub_dirc/modified_1.txt:7:do you know my favourite motto?
./sub_dirc/modified_1.txt:8:Nothing is possible
./sub_dirc/modified_1.txt:9:
./sub_dirc/modified_2.txt:2:I am 20 year's old.
./sub_dirc/modified_2.txt:3:Do you like us?
./sub_dirc/modified_2.txt:4:I want to make friends with you.
./sub_dirc/modified_2.txt:5:Remember my name, my name is KatE!
./sub_dirc/modified_2.txt:6:HAahah
./sub_dirc/modified_2.txt:7:do you know my favourite motto?
./sub_dirc/modified_2.txt:8:Open source is the best thing in the world!
./sub_dirc/modified_2.txt:9:
./grep_test.txt:2:I am 18 year's old.
./grep_test.txt:3:Do you like me?
./grep_test.txt:4:I want to make friends with you.
./grep_test.txt:5:Remember my name, my name is JACK!
./grep_test.txt:6:HAahah
./grep_test.txt:7:do you know my favourite motto?
./grep_test.txt:8:Knowledge isn't free, you have to pay attention.
./grep_test.txt:9:

1
grep -ri -A 1 "motto" ./
1
2
3
4
5
6
7
8
./sub_dirc/modified_1.txt:do you know my favourite motto?
./sub_dirc/modified_1.txt-Nothing is possible
--
./sub_dirc/modified_2.txt:do you know my favourite motto?
./sub_dirc/modified_2.txt-Open source is the best thing in the world!
--
./grep_test.txt:do you know my favourite motto?
./grep_test.txt-Knowledge isn't free, you have to pay attention.

You can make the command line more complex to get more specific data!

1
grep -ri -A 1 "motto" ./ | grep -v "motto"
1
2
3
4
5
./sub_dirc/modified_1.txt-Nothing is possible
--
./sub_dirc/modified_2.txt-Open source is the best thing in the world!
--
./grep_test.txt-Knowledge isn't free, you have to pay attention.

More specific:

1
grep -rih -A 1 "motto" ./ | grep -v "motto" | grep -v "^--$"

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
2
3
Nothing is possible
Open source is the best thing in the world!
Knowledge isn't free, you have to pay attention.

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 { action }
  • 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
2
3
4
5
6
7
8
ID      Name          Gender  Age  Class     Chinese  Math  English  Physics  Chemistry
2023001 John_Doe Male 18 Class_1 85 92 88 90 87
2023002 Alice_Smith Female 17 Class_2 78 85 80 82 79
2023003 Bob_Johnson Male 19 Class_1 92 88 95 89 94
2023004 Emma_Wilson Female 18 Class_3 65 72 68 70 62
2023005 Mike_Brown Male 17 Class_2 80 76 85 78 82
2023006 Lily_Davis Female 19 Class_3 88 90 92 87 91
2023007 Tom_Miller Male 18 Class_1 73 68 75 70 65
  • Printing Specific Fields
1
awk '{ print $1, $3 }' file.txt

  • Filtering Lines Based on a Condition
1
awk '$3 > 25 { print $0 }' file.txt

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
awk '{ print NR, $NF }' file.txt

  • 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
awk -F, '{ print $2 }' data.csv

Input (data.csv):

1
2
John,Doe,30,Engineer
Jane,Smith,25,Designer

Output:

1
2
Doe
Smith

  • 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
2
3
4
5
awk '
BEGIN { sum = 0 }
{ sum += $3 }
END { print "Total lines:", NR, "Sum of third field:", sum }
' file.txt

Output:

1
Total lines: 2 Sum of third field: 55

  • 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
awk '$2 ~ /Smith/ { print $0 }' file.txt

  • Conditional Statements

AWK supports if-else statements for more complex logic.

Example: Classify ages as “Young” or “Old”.

1
2
3
4
5
6
awk '{
if ($3 < 30)
print $1, "is Young"
else
print $1, "is Old"
}' file.txt

  • 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
2
3
4
5
awk '{ count[$3]++ }
END {
for (age in count)
print age, ":", count[age]
}' file.txt

  • 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
awk '{ print length($1) }' file.txt

  • Custom Functions

You can define custom functions in AWK for reusable logic.

Example: Define a function to calculate the square of a number.

1
2
3
4
5
6
awk '
function square(x) {
return x * x
}
{ print square($3) }
' file.txt

  • Output Redirection

AWK allows you to redirect output to files.

Example: Write the first field to a new file.

1
awk '{ print $1 > "output.txt" }' file.txt

References


Bash_commands
https://xiyuanyang-code.github.io/posts/Bash-commands/
Author
Xiyuan Yang
Posted on
February 17, 2025
Updated on
February 18, 2025
Licensed under