1. The Function Definition Format in shell is:
Function name (){
# Function body
}
The function definition must follow the principle first defined in use, such as defining the function print
#!/bin/shfunction print(){if [ $# -lt 1 ]then print “no parameter”;return 1;else ehco “$1,$2”;return 0;fi}ehco “print function is being invoked”print
The return statement above is the return value of the function. 0 indicates that the function is successfully run, and 1 indicates that the operation fails. If no return statement exists, the value generated by the last command of the shell function is used as the return value.
In addition to defining and using functions in a script, you can also write functions into a file and load them to call them.
For example, define the following function
#!/bin/sh#filename:guessnum.shfunction guess(){num1=$RANDOM;num=$num1%100;echo “please guess a number”while truedoprintf “input a number\n”read inpuif (($inpu == $num))thenprintf “right\n”;break;elseif (($inpu < $num))then printf “too low\n”;elseprintf “too high\n”;fi done}
Save this function as the guessnum. sh file, and locate the file by: <.> <space> <File Name>
That is, $. guessnum. sh
Check the loading status: set | grep guessnum
Execution function: guessnum
Delete function: unset guessnum
After deletion, load it again. The guessnum function can continue to be used.
The following is an introduction to the case statement. The basic format of the case statement in shell is
Case $ variable name in
Matching mode 1)
;;
Matching Mode 2)
;;
Matching Mode 3)
;;
Esac
#!/bin/bashprintf “input a character\n”;read ch;case $ch in [a-z])echo “lower”;;;[A-Z])echo “upper”;;;[^A-Za-z])ehco “not a character”;;;esac
The above code may be case-insensitive when running in the ubuntu environment, that is, the results of "lower" are displayed in both upper and lower case letters, the solution is to run the LANG = C command and run the program. C In LANG = C Represents the English ASCII environment.
The basic format of the for statement is as follows:
(1) for (Value assignment; condition; Operation statement ))
Do
# Statements
Done
The factorial method for calculating n is
#!/bin/shread –p “input a number” nums=1;for ((i=1;i<=$num;i++))s=$s*$i;echo ${{s}}
When the above code is executed in the ubuntu environment, the bad for loop Error may occur, Because ubuntu replaces bash with dash to speed up the startup, because dash is small and runs faster. To solve the problem, enter the sudo dpkg-reconfigure dash command in the terminal and select No in the options.
(2)... In...
Do
# Statement
Done
Generates 5 random numbers.
For k in 1 2 3 4 5
Do
Echo $ RANDOM
Done