Common scripts in Linux include bash and shell.
1
#!/bin/bashecho "hello bash" #display one message
Save the preceding content as a text file named me. The extension is arbitrary, but. Sh is often used as the extension.
Run the command chmod A + x me to add the execution permission for me. Then run the script in ternimal.
./mehello bash
2. Obtain input parameters
$ N is a natural number ranging from 1 to 9, representing the nth parameter in the input.
#! /Bin/bashecho $1 echo $2 Echo $3 run the script and the output is./Me I love youiloveyou
3. Define Variables
There cannot be spaces in the value assignment statement. When referencing a variable, you only need to add the $ symbol before the variable.
To avoid confusion, double quotation marks are often used to include variables to be referenced.
#! /Bin/Basha = ball = allecho "$ A" llecho all run the script and the output is:./mebllall
4. Condition Determination
if [ "$1" = "normal" ]then echo "this is normal case"elif [ -z "$1" ]then echo "no input, ignal..."fi
5 while []... do... donw statement
#!/bin/bashecho "please use add or delete or exit"ACTION="default"while [ -n $ACTION ]do read ACTION case $ACTION in add) echo "add somebody" ;; delete) echo "delete somebody" ;; exit) echo "complete" break ;; *) echo "invalide action, please re-enter" ;; esacdone
6. For Loop
Generally, for is used in combination with in to extract elements from a collection one by one and perform operations on the period. The following code shows
#!/bin/bashfor X in 1 2 3 4 5 hellodoecho $Xdone
Let's take another example.
'Symbol is! The key to the left of the symbol.
for X in `ls`doecho `basename $X`echo `dirname $X`done uname
For statement and if statement
Function: adds a. txt extension to a file without an extension in the current directory.
#!/bin/bash#rename files without ext name to txt file.for X in `ls`do Base="`basename $X`" if [ -z `echo $Base | grep "\."` ] then `mv $Base $Base.txt` echo $Base fidone
7 Functions
#! /Bin/bashstrcat () {out = "$1" $2 "Return 0} strcat2 () {echo "$1" $2 "return 3} A =" bird "B =" Mouse "out =" "strcat $ A $ becho $ outout2 = 'strcat2 $ A $ B 'echo $? # // Echo $ out2 of the returned result of the previous command # Run the script and the output is:./mebird mouse3bird mouse
When defining a function, you do not need to define parameters. $1 and $2 are directly used to represent the nth parameter.
Return can be used to return integer values. The return value cannot be a string. If no value is specified, the return value is 0 by default.