- Variable assignment
- Variable access
- Variable input
4.1 variable assignment
In shell programming, all variable names are composed of strings and do not need to be declared. To assign a value to a variable, the format is as follows:
Variable name = Value
Note:
No space before and after equal sign (=)
For example:
X = 6
A = "how are you"
Assign the value of 6 to variable X, and assign the value of string "how are you" to variable.
4.2 Access variable value
To access the variable value, you can add a dollar sign "$" before the variable, for example:
[[Email protected] bin] # A = "how are you"
[[Email protected] bin] # echo "He juest said: $"
A is: Hello World
Values assigned to another variable can be written as follows:
Variable 2 =$ Variable 1
For example:
X = $ I
I ++ can be written as follows:
I = $ I + 1
4.3 enter the variable value on the keyboard
In shell programming, the variable value can be read from the keyboard as a string in the format:
Read variable
For example:
[[Email protected] bin] # Read Str
Read is a READ command that reads strings from the keyboard to Str.
Example 4: compile a shell program test3. When the program is executed, read a directory name from the keyboard, and then display the information of all files in the directory.
Analysis:
The variable that stores the directory is directory, and its read statement is:
Read directory
Command: ls-
[[Email protected] bin] # vi test3
#! /Bin/sh
Echo "Please input name of directory"
Read directory
CD $ directory
Ls-l
(2) Set permissions
[[Email protected] bin] # chmod + x test3
(3) Execution
[[Email protected] bin] #./test3
Note:
Enter the path "/"
Instance 5: run the program test4, read the values of X and Y from the keyboard, perform addition operations, and finally output the results.
(1) Use VI to edit the program
[[Email protected] bin] # vi test4
#! /Bin/sh
Echo "Please input x Y"
Read X Y
Z = 'expr $ x + $ y'
Echo "the sum is $ Z"
(2) Set permissions
[[Email protected] bin] # chmod + x test4
(3) Execution
[[Email protected] bin] #./test4
45 78
The sum is 123
Note:
Expression Total = 'expr $ total + $ num' and num = 'expr $ num + 1'. the symbol "'" is the "'" key in the upper left corner of the keyboard.