1. Getting to Know the Shell
The shell is an interpreter between the system kernel and the user, a bit like a translator. A script is a file in a particular language that runs in a predefined order, such as Shell, Python, Ruby, or JavaScript.
How to approach writing a script
Clarify the task steps->organize the statements->complete the file structure
For example, add a user named tom and set the password to 123123
Clarify the task steps:
Add the user
useradd tomSet the password
passwd 123123
Organize the statements:
|
|
Complete the file structure:
|
|
Run the file
chmod +x uad,.sh./uad.shsh uad.shsource uad.sh
2. Combining Shell Commands
Pipes: command1 | command2
Find aa in the test filecat test | grep aa
Count the files ending in .conf under /etcfind /etc -name "*.conf” -type f | wc -l
View the httpd processes:ps -aux | grep httpd
Redirection
| Type | Operator | Purpose |
|---|---|---|
| Input redirection | < | Read data from the specified file |
| Output redirection | <, << | Overwrite or append output to the specified file |
| Standard error output | 2>, 2>> | Overwrite or append error messages to the specified file |
| Combined output | &>, &>> | Overwrite or append both standard output and errors to the specified file |
Check the Linux kernel versionuname -r
Write the result to version.txtuname -r > version.txt
Since there's no version2.txt, this gives an errorcat version.txt version2.txt
How do you send the error message to a file? Use 2>cat version.txt version2.txt 2> error.txt
Logical separators
- AND: &&
- OR: ||
- Command separator: ;
Logical ANDecho "haha" && echo "heihei"
Logical ORecho "haha" || echo "failed"
Use logical AND or OR to check whether a command succeeded. Both of these check whether a directory was created successfullymkdir test/a 2>/dev/null && echo "success"mkdir test/a 2>/dev/null || echo "failed"
The command separator separates multiple commandscd boot/grub;ls -ls grub.conf
3. Shell Variables
Definition and assignment
Format: name=value
Referencing variables
Format: $name, ${name}
|
|
Double quotes: allow references and \ escapes
|
|
Double quotes reference directly and output the value of $name
Single quotes: no references, no escapes
|
|
Single quotes can't reference, so the output is still the literal $name
Backticks `` or $( ): followed by a command
The command above outputs the Linux kernel version directly
Environment variables
Used to record or set runtime parameters; env lists all environment variables
- Set by the system: USER, LOGNAME, HOME, SHELL…
- Set by the user: PATH, LANG, CLASSPATH…
echo $USER $HOME $SHELL
Controlled by the system or script; can't be assigned manually
$?: whether the previous command succeeded; returns a status code, 0 for success, non-zero for errors
$0: the script's own name
$1-$9: the first through ninth positional parameters
$*: all positional parameters on the command line
$#: the number of positional parameters on the command line
mkdir test
echo $?, success, returns 0
0
mkdir /1/2/3,
echo $?, since 1 and 2 don't exist, creation fails and returns non-zero
1
Write a script that uses the variables above:
|
|
4. Arithmetic and Number Handling
Integer arithmetic
Two formats:the expr command evaluates an expressionexpr number1 operator number2
outputs the number directly
The $[] expression, arithmetic substitution
$[number1 operator number2]
the result needs echo to output
Operators: + - * / %
expr 322 / 322: since is a wildcard in Linux, it must be escaped when used as a multiplication sign
A few number-handling tips
Increment and decrement variables
let var++
let var–
|
|
Generate random numbers with RANDOM, ranging from 0 to 32767echo $RANDOM
Take the remainder of a random number to get a random number from 0 to 99echo $[RANDOM%100]
seq generates number sequences
seq first last
seq first step last
seq 4seq 3 6seq 3 3 19
Decimals
The shell can't handle decimals directly; you need the bc command. For example, to calculate with decimalsecho 433.44-43.5 | bc
Calculate with decimals and keep four decimal placesecho "scale = 4;10/3" | bc
5. String Handling
Substrings
- Splitting paths: the dirname and basename commands
- expr: expr substr $var1 start length, numbering starts at 1
- The ${} expression: ${var:start:length}, numbering starts at 0
dirname for the path, basename for the file name
|
|
Substring with expr
|
|
Substring with ${}
|
|
String replacement
Replacement with the ${} expression${var/old/new} replaces only the first old with new${var//old/new} replaces every old in the variable; use two slashes //
Random strings
How random strings are generated:
- /dev/urandom (generates random characters of all kinds)
- /usr/bin/md5sum (turns them into standard encoded characters)
- /bin/cut (cuts out the characters you need)
Example:
First convert the random device characters to ASCII characters and assign them to var, then cut them
echo $var | cut -b start-end; both start and end can be omitted.
|
|
6. Conditional Tests
What a test is
A test is a command; its $? return value tells you whether the condition holds
Format
Two formats: test expression
or [ expression ], with spaces inside the brackets
How to practice
Follow it directly with && echo YES to see the result
[ expression ] && echo YES
File status checks
-e: whether the target exists
-d: whether it's a directory
-f: whether it's a file
[-f “/boot/fstable”] && echo yes[-f “/etc”] && echo yes
Permission checks
-r: whether it's readable
-w: whether it's writable
-x: whether it's executable
|
|
Integer comparison
-eq: equal
-ne: not equal
-gt: greater than
-lt: less than
-ge: greater than or equal
-le: less than or equal
|
|
String matching
= the two strings are equal
!= the two strings are not equal
|
|
7. if Statements
Single-branch if statement
|
|
Example: check the backup directory /opt/repo and create it if it doesn't exist.
|
|
Example: check whether a target host is alive and show the result
|
|
Multi-branch if statement
if condition1
then commands1
elif condition2
then commands
…
else
commandsN
fi
Example: grade a score as excellent / pass / fail
|
|
8. for Loops
Syntax
|
|
Check whether IP addresses are in the host address list
|
|
Usage examples:
|
|
Output the contents of hosts word by word
|
|
Add user accounts in bulk from users.txt, one per line, setting the initial password to 123456 and requiring a change at first login.
|
|
Check the status of hosts in an IP range, 192.168.4.1 - 192.168.4.10
to see whether they respond to ping.
|
|
9. case Statements
Syntax
|
|
A simple service control example
|
|
Examples
Identify the type of user input
|
|
Write a service script, sleepd
* Responds to the start and stop control arguments
* Hands the service over to chkconfig for management
|
|
chkconfig setup
Set the chkconfig parameters at the top of the script
Add it as a system service
Run this in the /etc/init.d/sleepd directory
chkconfig -add sleepd
10. awk, the Text Processing Tool
What it does
awk is named after the first letters of its three authors' names
Checks input based on pattern matching
prints the desired results to the screen
Format
awk 'pattern{action}' file1 file2
awk 'NR==1{print} /etc/hosts # prints the first line of hosts; NR is a built-in awk variable for the line number
You can also use head -1 /etc/hosts for the same result
A few common built-in variables:
NR the number of the line being processed (line number), number row
FS the field separator, space or tab by default
$n the nth field of the current line
$0 the entire text of the current line
Examples
|
|
Print lines 1 through 3awk 'NR==1,NR==3'{print}' test-awk.txt
Print lines 1 and 3awk 'NR==1||NR==3'{print}' test-awk.txt
Print all odd linesawk 'NR%2==1{print}' test-awk.txt
Print all even linesawk 'NR%2==0{print}' test-awk.txt
Regex matching uses two slashes: /chars/
List all lines containing aawk '/a/{print}' test-awk.txt
List lines ending in bashawk '/bash$/{print}' test-awk.txt
awk's default separator is space or tab, so you can print specific fields, for example fields 1 through 3 of lines 1 through 3
awk ‘NR==1,NR==3{print $1,$3} test-awk.txt
Besides the default separator, you can set one with -F. For example, using a dot as the separator, print the second field of the line whose third field is 185. $2 is the second field, and $0 prints the whole lineawk -F. '$3=="185”{print $2}' test-awk.txt
11. Text Processing with sed
sed stands for stream editor. It doesn't just print; it can also replace and delete, so it's more powerful. It filters, modifies, and deletes text based on pattern matching.
Format
sed 'command' file1 file2 …
sed -n 'command' file1 file2 ……, -n only prints the lines you ask for
sed -i 'command' file1 file2 ……, -i edits the file in place
Command format
[address1[,address2]]operation
Separate multiple commands with semicolons
The most common operations
p print lines
n read the next line (skip the current line)
d delete text
s substitute text
a append text
Examples
|
|
Note: separate n and p with a semicolon
Using regular expressions with sedsed -n '/a/,$p' test-sed.txt
Prints from the first line containing a through the last line; $ means the last line
sed -n /\<This\>/p' test.txt
Prints lines containing the word This as a whole word; the backslashes escape the angle brackets
Delete matching lines
|
|
Replace matching text
|
|
None of the sed commands above use flags, so they only show the result without changing the file itself. To edit the file directly, use the -i flag.
