Getting Started with Shell programming
One, variable assignment and arithmetic operation
Example code:
A=1echo $alet b= $a +1echo $bc =$[a+b]echo $cd =$[c*2]echo $dlet e=d*2echo $ef =$[e%5]echo $f
Note the "=" number must not have spaces on either side
The code snippet above will output:
1
2
3
6
12
2
Two, array
1, assign Value
Sample code
Declare-a arr1= (1 2 3 4) echo ${arr1[0]}arr2= ("China" "Japan" "Korea") echo ${arr2[0]}arr3[0]=100echo ${arr3[0]}
The code snippet above will output:
1
China
100
2, iterating through the array
Sample code
Arr2= ("China", "Japan" "Korea") for V in ${arr2[@]};d o echo ${v}done
The code snippet above will output:
China
Japan
Korea
Note: the @ symbol in ${arr2[@]} represents the list of elements
Three, condition judgment
1, integer comparison
-lt, less than
-le, less than or equal to
-eq, equal to
-ge, greater than or equal to
-GT, greater than
-ne, not equal to
Example code:
a=1b=2if [$a-lt $b];then echo "A<b is true" else echo "A<b is false" fic=3if [$a-lt $b] && [$c-gt $b] And then echo "A<b && c>b are true" else echo "A<b && C>b is false" fi
The code snippet above will output:
A<b is True
A<b && C>b is True
2, string comparison
S1 = s2
S1! = S2
S1 > S2
S1 < S2
-N s1,s1 not null, length greater than 0
-Z s1,s1 is null, length is zero
Example code:
s1= "China" s2= "China" if [$s 1= $s 2];then echo ' s1=s2 is true ' else echo ' s1=s2 is False ' fi
The code snippet above will output:
S1=s2 is True
3, file attribute judgment
-A file1:file1 exists
-D File1:file1 exists and is a directory
-e file1:file1 exists, same-a
-F File1:file1 exists and is a regular file (not a directory or other special type of file)
-R file1: Read permission
-S file1: file exists and is not empty
-W file1: Write permission
-X file1: have permission to execute or have search for directory
-N file1: File changed after last read
-O file1:own files that belong to
-G file1:group files that belong to
File1-nt File2:file1 is newer than file2 and is subject to last updated time
File1-ot File2:file1 is older than file2, whichever is the last update time
Example code:
If [-D "/home"];then echo "/home dir exists" else echo "/home dir NOT exists" fi
The code snippet above will output:
S1=s2 is True
/Home dir is exists
Four, function definition
function parameter schematic:
$ A: Indicates the function name
$: 1th parameter
$ A: 2nd parameter
Example code:
A=1function func1 () {local b=2 return $[a+b+$1]}func1 3b=$?echo $b;
The code snippet above will output:
6
Attention:
The return value of the Shell language function differs from the traditional language, and the return value in the shell usually refers to the return value after execution of the command, success 0, failure 1;
The example code above has a return statement stating that the function has customized the return value, so you can use $? View this return value.
A is a global variable and B is a local variable.
Getting Started with Shell programming