Shell study
1. Exit Status
If the command executed successfully (or true), the value of $? is zero. If the commandfailed for some reason,$? Would containapositive integer between 1 and 255, inclusive. A failed command usually returns 1.
2, testing an Expression
The test command evaluates many kinds of expressions,from file properties to integers to strings.
1) file Tests,a file ' s existence can be tested with-e (or the nonstandard-a). The type of file can is checkedwith-f for a regular file,-D for a directory,and-hor-lforasymboliclink. For example:
test-f/etc/fstab# #trueifaregularfile
test-h/etc/rc.local# #trueifasymboliclink
[-X "$HOME/bin/hw"]# #trueifyoucanexecutethefile
[[-s$home/bin/hw]]# #trueifthefileexistsandisnotempty
2) Comparisons between integers use The-eq,-ne,-gt,-lt,-ge,and-le operators.
Below is a example:
$ test1-eq1
$ echo$?
3) String tests,the= operator Tests for Equality, in other words,whether they is identical;
! = tests for inequality. The-zand-n operators return successfully if their argumentsare empty or nonempty.
Here Ara some example:
Test "$a" = "$b"
["$q"! = "$b"]
$ [-Z ""]
$ echo$?
0 #判空
$ test-n ""
$ echo$?
1
3, [[...]]:evaluate an Expression
4, ((...)): Evaluate anarithmeticexpression
5, Conditionalexecution
Example
Readname
If[[-z$name]]
Then
echo "Nonameentered" >&2
exit1# #Setafailedreturncode
Fi
Readnumber
if ((number>10))
Then
printf "%distoobig\n" "$number" >&2
Exit1
Else
printf "youentered%d\n" "$number"
Fi
6, conditionaloperators,&&and| |
Listscontainingtheandandorconditionaloperatorsareevaluatedfromlefttoright.a
Commandfollowingtheandoperator (&&) Isexecutedifthepreviouscommandis
Successful. Thepartfollowingtheoroperator (| |) Isexecutedifthepreviouscommand
Fails.
7. Case
The syntax is as follows:
Casewordin
PATTERN) COMMANDS;;
PATTERN) COMMANDS;; # #optional
Esac
8. Loop
1) While syntax:
While<list>
Do
<list>
Done
Instance:
N=1
while[$n-le10]
Do
echo "$n"
n=$ (($n + 1))
Done
2) util rarely used, with while just the opposite (cyclic conditions fails), the example is as follows,
N=1
until[$n-gt10]
Do
echo "$n"
n=$ (($n + 1))
Done
3) for, example:
For ((N=1;n<=10;++n))
Do
echo "$n"
Done
4) Break
Do
Readx
[-Z "$x"]&&break
Done
5) Continue
fornin{1..9}# #SeeBraceexpansioninChapter4
Do
x= $RANDOM
[$x-le20000]&&continue
echo "n= $nx = $x"
Done
17th Shell Programming Basics (2)