Linux shell Programming

Source: Internet
Author: User
Tags case statement

First, the meaning of variable $#,[email protected],$0,$1,$2,$*,$$,$ in Linux:

Script tests can be used to differentiate the specific roles and usages of these variables.

The script is as follows:

# vim Variable#!/bin/shecho "number:$#" echo "Scname:$0" echo "First:" echo "Second:$2" echo "Argume:[email protected]" echo "Show Parm list:$*" echo "Show Process id:$$" echo "Show Precomm stat: $?": Wq

Assigning Script Execution permissions

# chmod +x Variable

Execute script

#./variable aa bbnumber:2scname:./variablefirst:aasecond:bbargume:aa bbshow parm list:aa bbshow Process Id:24544show Precomm stat:0

By displaying the results you can see:

$# is the number of arguments passed to the script. $ is the name of the script itself. $ is the first parameter passed to the shell script, and the second argument that is passed to the shell script is [email protected] is a list of all the parameters passed to the script $* is to display all parameters passed to the script in a single string, unlike positional variables, which can be more than 9 $$ is the current process ID number for the script to run? is to display the exit status of the last command, 0 means no error, and the other indicates an error ############################################################################ Two. Read-p usage of Linux shell

The purpose of the read command under the shell is to read the input from the standard stream and put the contents of the read into a variable.

#!/bin/bashecho-e "Please enter your test:" Read Testreadecho $TESTREAD ######################################### #实例2 #  !/bin/bashmum=$1mum=${mum:-3}            #变量替换 # #当 $mum After the value is greater than or equal to 3, do the. if [$mum = "1"];thenecho "test environment ..." elif [$mum = "2" ];thenecho "Production environment" Elseecho "Please enter 1 or 2, or click the Enter key ..." fiecho-e "\033[35m---------you enter a number $mum!!! $in \033[39;49;0m "Echo  "  Press any key to continue "                 # Prompt to continue by pressing any key ... read key                           
Third, Shell learning notes of the loop statement for and while

Loop statement: For while
1.) The FOR Loop statement is used when the number of loops is known.
2.) While loop statement is used when the number of cycles is not known, the operation of adding 1 to the variable can be written as "let,i++" or the expr variable 1 operator variable

For loop structure:

For variable name in value list do                                               command sequence done                                                 

While loop structure:

While   condition test command do command sequence done

For loop instance:

[Email protected] source]# more for. sh#!/bin/Bash for((i=1;i<Ten; i++))  Doecho $i done or executed (the result is the same in two ways). #!/bin/Bash forIinch' SeqTen` Doecho $i Done results: [[email protected] source]# sh for. SH123456789example 2:for loop creation user script: #! /bin/Bash forIinch{1...Ten}  Douseradd studet$i echo Password| passwd--stdin studet$i Done
For Loop Instance

While loop instance:

While Loop instance: #!/bin/SH echo"Please input the num:"Read num sum=0I=1Signal=0  while[[$signal! =1 ]]  Do if[$i-eq $num] then let"signal=1" Let"sum+=i"Echo"1+2 、、、 + $num = $sum" Else Let"Sum=sum+i" Let"i++"fi done instance 2:while loop ... #!/bin/bashcheckdays=7 while[$checkdays-ge4 ] DoRQ= ' Date +%y-%m-%d--date="$checkdays days ago"`        [ -f/usr/local/tomcat7/logs/localhost. $rq. log] &&{tar zcf localhost. $rq. log.tar.gz localhost. $rq. log} let Checkdays-=1# # # #属于递减的循环 ... done after the results are as follows: [[email protected]~]# Sh-x the. SH+ checkdays=7+'[' 7-ge4 ']'+ + Date +%y-%m-%d'--date=7 days ago'+ rq= the- -- -+'['-f/usr/local/tomcat7/logs/localhost. the- -- -. log']'+ Let checkdays-=1+'[' 6-ge4 ']'+ + Date +%y-%m-%d'--date=6 days ago'+ rq= the- -- -+'['-f/usr/local/tomcat7/logs/localhost. the- -- -. log']'+ Let checkdays-=1+'[' 5-ge4 ']'+ + Date +%y-%m-%d'--date=5 days ago'+ rq= the- -- -+'['-f/usr/local/tomcat7/logs/localhost. the- -- -. log']'+ Let checkdays-=1+'[' 4-ge4 ']'+ + Date +%y-%m-%d'--date=4 days ago'+ rq= the- -- -+'['-f/usr/local/tomcat7/logs/localhost. the- -- -. log']'+ Let checkdays-=1+'[' 3-ge4 ']'[[Email protected]~]#
While Loop instanceFour, the shell study note condition judgment statement if

Conditional Judgment statement: if

If  condition Test command  then      command sequence 1  else      command sequence 2  fi

Instance:

#!/bin/bash#install nginx-1.10.2if [!-d/usr/local/src];then  echo "Not dircetry!!" Else  echo "Is this Dirctroy" fi

2. Multiple conditional judgment statement: If/else

If [conditional test command];then     command sequence 1elif [conditional Test command];    then command sequence 2elif [conditional Test command];   Then command sequence 3else   command sequence 4fi

Instance:

#!/bin/Bashsystem= ' uname-s 'if[$system ="Linux"];thenecho"Linux"Elif [$system="Windows"];thenecho"Windows"Elif [$system="Solaris"];thenecho"Solaris"ElseEcho"What ??"fi
Statement judgment system is that type of operating system

1. Integer judgment

-eq equals, such as: if ["$a"-eq "$b"]    -ne not equal, such as: if ["$a"-ne "$b"]    -gt greater than, such as: if ["$a"-gt "$b"]    -ge greater than equals, such as: if ["$a "-ge" $b "]    -lt less than, such as: if [" $a "-lt" $b "]    -le less than equals, such as: if [" $a "-le" $b "]     greater than (requires double brackets), such as: ((" $a ">" $b "     ) >= is greater than or equal (requires double brackets), such as: (("$a" >= "$b"))    small data comparisons can be used with awk

2. Judgment of documents

-r file user readable as true-W file user can write as true-X file user can execute as true-F file file as a true-D files file for a real True-B file files are block special files for true-s file files non-0 o'clock true-t when file descriptor (default = 1) Specifies that the device is terminal true [-F ' somefile "]: Determines whether a file [-X]/bin/l S "]: determine if/bin/ls exists and has executable permissions [-n ' $var]: Determine if the $var variable has a value [" $a "=" $b "]: Determine whether a $ A and $b are equal

3. Complex logic judgment

-A   with-O or!  Non-

4. String Judgments

STR1 = str2 When two strings have the same content, the length is true str1! = str2 when the string str1 and str2 are true-n str1 when the length of the string is greater than 0 is true (string non-null)-Z str1 when the string length is 0 true (empty string) str1   True when string str1 is non-empty
Five, Shell learning notes of the multi-branch statement-case

Multi-Branch Statements: Case Multi-branch if statements can often be modified as case statements.

Case $ variable name in                mode 1)            command sequence 1            ;;                Mode 2)            command sequence 2         ;;                 *)            sequence of commands executed by default     ;;             

2. The case statement has the following structural characteristics:

The case line end must be the word "in", and each pattern must be terminated with a closing parenthesis ")".

Double semicolon ";;" Indicates the end of the command sequence.

The matching pattern uses square brackets to denote a contiguous range, such as [0-9]; Use the vertical bar symbol "|" Represents or.

The Last "*" indicates the default mode, and the command sequence after "*" will be executed when all previous modes cannot match the variable.

3.case Statement instance:

1.) The user enters a character from the keyboard and determines whether the character is a letter, number, or other character, and outputs the appropriate hint.

#!/bin/bashread-p "Press some key, then press RETURN:" Keycase $KEY in[a-z]| [A-z]) echo "It's a letter.";; [0-9]) echo "It s a digit."; *) echo "It s function keys, Spacebar or other ksys." Esac

2.) Many of the daemon will be accompanied by a management Shell Script,apache attached to Apachectl. These management programs are written in shell script, and a shell script that manages inetd is shown below.

#!/bin/sh case $ in     start | begin | commence)        /usr/sbin/inetd     ;;     Stop | End | Destroy)        killall inetd     ;;     Restart | Again)        killall-hup inetd     ;;     *)        echo "Usage:inetpanel [Start | Begin | Commence | Stop | End | Destory | Restart | Again] ";     Esac

For example, use case to write a script that extracts the war package.

#more initjar.sh#!/bin/bash######################################################### #DDIR =~/sourcesproject=$ 1pwd= ' pwd ' dconf=~/$PROJECT/web-inf/classescase $ fore) test! -D ~/$PROJECT && mkdir ~/$PROJECT cd ~/$PROJECT && rm-rf./* JAR-XF $DDIR /$PROJECT. War cat $DCONF/server.properties.online > $DCONF/server.properties cat $DCONF/da Tabase.properties.online > $DCONF/database.properties cat $DCONF/merchantinfo.properties.online > $DCON F/merchantinfo.properties cat $DCONF/.. /web.xml.online > $DCONF/...        /web.xml;; ETEN) Test! -D ~/$PROJECT && mkdir ~/$PROJECT cd ~/$PROJECT && rm-rf./* JAR-XF $DDIR /$PROJECT. War cat $DCONF/server.properties.online > $DCONF/server.properties cat $DCONF/da Tabase.properties.online > $DCONF/database.propErties #cat $DCONF/merchantinfo.properties.online > $DCONF/merchantinfo.properties; PP-BMS) Test! -D ~/$PROJECT && mkdir ~/$PROJECT cd ~/$PROJECT && rm-rf./* JAR-XF $DDIR /$PROJECT. War cat $DCONF/server.properties.online > $DCONF/server.properties cat $DCONF/da Tabase.properties.online > $DCONF/database.properties #cat $DCONF/merchantinfo.properties.online > $DCO        Nf/merchantinfo.properties;;                *) echo $ "Usage: $ Fore|eten|pp-bms|passport|pp-web2|toloan|report|app}" retval=2 ;; Esacexit $RETVAL

A backup script written with case.

#more backup.sh#!/bin/bash############################### Discrition:backup Project of Tomcat by manual# example: ~/bi N/backup.sh fore# write by Frank at 2014/03/11############################# #BAK_DIR =/apps/product/backupeten_dir=/ apps/product/tomcat_eten/webapps/etenfore_dir=/apps/product/nginx/htdocs/p2ptomcat/forebms=/apps/product/ Tomcat_eten/webapps/pp-bmsday_dir= ' Date +%y%m%d ' time= ' date +%y%m%d%h%m ' mkdir-p ${bak_dir}/${day_dir}case ' in ET EN) CD $BAK _dir cp-a $ETEN _dir $BAK _dir tar-czf $ $TIME. tgz $ &&amp ;        RM-RF $ MV $ $TIME. tgz $DAY _dir/exit 0; Fore) CD $BAK _dir cp-a $FORE _dir $BAK _dir tar-czf $. $TIME. tgz $ &AMP;&A mp        RM-RF $ MV $ $TIME. tgz $DAY _dir/exit 0; Pp-bms) CD $BAK _dir cp-a $BMS $BAK _dir tar -czf. $TIME. tgz $ && rm-rf mv $ $TIME. tgz $DAY _dir/exit 0        ;; *) echo "$ {Eten|fore|pp-bms}" exit 2;; Esac

Reference Document: Http://blog.sina.com.cn/s/blog_af6bb6bc0102uwb9.html

Linux shell Programming

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.