# Notes, Shell Script

### Acknowledge

• What is shell script?
A shell script is a file containing a series of commands.

### The first shell script

hello_world.sh

• make it executable

### Build a program

#### here documents

• By default, single and double quotes within here documents lose their special meaning to the shell.
• If we change the redirection operator from “<<” to “<<-“, the shell will ignore leading tab characters in the here document. This allows a here document to be indented, which can improve readability.

### control: if branching

#### test expression

The test command returns an exit status of zero when the expression is true and a status of one when the expression is false.

#### test string expression

Expression Is Ture If…
string string is not null.
-n string The length of string is greater than zero.
-z string The length of string is zero.
string1 = string2 or string1 == string2 string1 and string2 are equal. Single or double equal signs may be used, but the use of double equal signs is greatly preferred.
string1 != string2 string1 and string2 are not equal.
string1 > string2 sting1 sorts after string2.
string1 < string2 string1 sorts before string2.

#### test integer expression

Expression Is Ture If…
integer1 -eq integer2 integer1 is equal to integer2.
integer1 -ne integer2 integer1 is not equal to integer2.
integer1 -le integer2 integer1 is less than or equal to integer2.
integer1 -lt integer2 integer1 is less than integer2.
integer1 -ge integer2 integer1 is greater than or equal to integer2.
integer1 -gt integer2 integer1 is greater than integer2.

#### compound command, enhanced test expression

[[ expression ]]: it is similar to test and it supports all of its expressions.

Another added feature of [[ ]] is that the == operator supports pattern matching the same way pathname expansion does. For example:

(( arithmetic expression )): it is used to perform arithmetic truth tests.

#### combine expressions

Logical Operators
|Operation| test| [[ ]] and (( ))|
|:-:|:-:|:-:|
|AND |-a| &&|
|OR| -o| |||
|NOT| !| !|

We also include parentheses around the expression, for grouping

#### two control operators, can perform branching

command1 && command2
command1 || command2

### Keyboard input

• If read receives fewer than the expected number, the extra variables are empty.
• If read receives more than the expected number, the final variable will contain all of the extra input.
• If no variables are listed after the read command, a shell variable, REPLY, will be assigned all the input.

#### IFS (Internal Field Separator)

The shell allows one or more variable assignments to take place immediately before a command.
These assignments alter the environment for the command that follows.
The effect of the assignment is temporary; only changing the environment for the duration of the command.
In our case, the value of IFS is changed to a colon character.

The <<< operator indicates a here string.
A here string is like a here document, only shorter, consisting of a single string.
We might wonder why this rather oblique method was chosen rather than:

The explanation has to do with the way the shell handles pipelines.
In bash (and other shells such as sh), pipelines create subshells (subshells is the subprocesses).
Subshells in Unix-like systems create copies of the environment for the processes to use while they execute.
When the command exits, the subshell and its environment are destroyed.
This means that a subshell can never alter the environment of its parent process.
Then the effect of the assignment is lost.

### Flow control: while/until loop

#### while

break and continue

• redirection

• pipe

### Stay out of trouble

#### logical errors

• incorrect conditional expressions.
• “Off by one” errors.
• Unanticipated situations.

#### debugging

• isolate the area related to problem
commenting out the code sections the code
• tracing
• echo more messages
• a method of tracing of bash

### Flow control: case branching

The patterns used by case are the same as those used by pathname expansion. Here are some valid patterns:
a): Matches if word equals “a”.
[[:alpha:]]): Matches if word is a single alphabetic character.
???): Matches if word is exactly three characters long.
*.txt): Matches if word ends with the characters “.txt”.
*): Matches any value of word. It is good practice to include this as the last pattern in a case command; that is, to catch any possible invalid values.

#### match more the one test

In bash prior to version 4.0 there was no way for case to match more than one test.
Modern versions of bash, add the ;;& notation to terminate each action, we can do this:

### Positional parameters

Each time shift is executed, the value of $2 is moved to $1, the value of $3 is moved to $2 and so on.
The value of $# is also reduced by one. In addition to $0, which never changes.

#### group positional parameters

“\$@” is by far the most useful for most situations, because it preserves the integrity of each positional parameter.

#### a complicated application

• Output file -f or --file
• Interactive mode -i or --interactive
• Help -h or --help

### control: for loop

#### the original for command’s syntax

If the optional in words portion of the for command is omitted, for defaults to processing the positional parameters.

### Strings and numbers

omitted
Strings and number

### Arrays

• shell arrays is 0-based.
• one way to create an array

• usually in the following way

• output the whole array
(a small mistake in the book, corrected)

• determine the number of elements

• find the index of array used

• sort the array

• delete an array

• any reference to an array variable without a subscript refers to element zero of the array

• associative array
associative arrays can only be created with the declare command using the new -A option

### Odds and ends

• group command or subshell
• process substitution
• trap
• temp file
mktemp

• asynchronous execution
wait

• named pipe

mkfifo

### Summay

Well, we have completed our journey. The only thing left to do now is practice, practice, practice. Even though we covered a lot of ground in our trek, we barely scratched the surface as far as the command line goes. There are still thousands of command line programs left to be discovered and enjoyed. Start digging around in /usr/bin and you’ll see!

1. 除非注明，本博文即为原创，转载请注明链接地址
2. 本博文只代表博主当时的观点或结论，请不要恶意攻击
3. 如果本文帮到了您，不妨点一下 下面分享到 按钮，让更多的人看到