Shell programming basics-Quick Start to Syntax

Source: Internet
Author: User

Shell programming basics-Quick Start to Syntax

Simply put, shell is a file containing several lines of Shell or Linux commands. For a large number of commands that can be used multiple times in a single compilation, you can save them in a separate file for future use. Generally, shell scripts are suffixed with. sh. The first line must specify which shell is required by the system to explain the user's shell program, such :#! /Bin/bash ,#! /Bin/sh. Here we use #! /Bin/bash.

Generally, shell is composed of Linux commands (External commands), Shell (Internal commands), control statements, and comment statements, similar to the batch processing files (. bat) in windows ). Note that we need to use chmod + x name. sh to execute the shell script.

(1) variables and Arrays

1. Use type to determine whether it is an internal command: type cmd

2. If a null value is assigned to the variable, the variable is directly followed by a carriage return and there cannot be spaces on both sides of the equal sign.

3. echo $ a outputs the value of

4. export A: Set A as A global variable.

Show the variable value: echo $ A, {} is used to prevent confusion. For example, the output value of A is followed by the B character: echo $ {A} B.

5. Delete the variable: unset

6. Show all variables (including local): set; set | grep A (show A variable); env: show global variables (environment variable); initialize global variables: export A = 200. In addition, global variables should be capitalized according to the Convention: export LANG

Note: global variables can be accessed in all shell environments. If the parent Shell process generates a sub-Shell process, the environment variables can be inherited and copied.

7. Read-Only variables: readonly myvar

8. location Parameter (command line parameter): A location parameter is a special set of built-in variables. It is usually used by shell scripts to accept parameters from the command line or by functions to save the parameters passed to him. It is equivalent to argv in C language. $1 indicates the first parameter, and $2 indicates the second parameter .... after $9, enclose the numbers in curly brackets. $ {10}; $0 indicates the file name of the current script.


Test procedure:

#! /Bin/bash # Test location parameters and other special parameters # usage:/target. sh parameter 1 parameter 2IFS = # echo shell script name is: $0 echo the count of parameters: $ # echo first param = $1 echo second param = $2 echo '$ * =' $ * # display all location parameter strings echo '"$ *" = "$ *" 'echo '$ @ =' $ @ echo '"$ @" =' "$ @" echo '$ =' $ # display the current process ID echo $!

 

Array definition and initialization: arr = (math Chinese English)

Array reference: 1. Reference variable: $ {arr [0]} 2. Number of Arrays: $ {# arr [*]} 3. All elements: $ {arr [*]}

Array assignment: arr [0] = chemial

 

Note that the shell array can be discontinuous, which is different from other languages, such as: arr [0], arr [1], arr [2], arr [5] is allowed. Their output (if the previous value is the same as the subscript), the array output is 0 1 2 5, and the number is 4.

(2) Input and Output

-P indicates the prompt;-t indicates the timeout time; echo $ REPLY; echo-n indicates that the carriage return is not output;-e "\ t" indicates the escape option.

Echo color output and cursor Positioning

\ 33 indicates that the escape starts. The format is [number m, and the color is changed from the cursor.

 

\ 33 [30 m -- \ 33 [37 m set foreground color \ 33 [40 m -- \ 33 [47 m set background color \ 33 [y; xH set cursor position example: echo-e "\ 33 [31 mthis is a test" echo-e "\ 33 [10; 5 h \ 33 [31; 46 mthis is a test "echo-e" \ 33 [0 m"

 

(3) characters and test statements

For arithmetic expansion, note: there must be spaces at both ends of the symbol!

Expression test:

String test:

 

Check null values

["$ Name" = ""]

[! "$ Name"]

["X $ {name}" = "X"]

Note: There must be spaces on both sides of the string test.

 

You can also use (), but the two are different. [] can only be paired with symbols such as-eq, while () can only be equal to>, <=.

In addition, [[expr1 & expr2] and so on are also possible. (|)

Summary of the test:

(4) condition and loop statements

If statement:

 

if [ $# -ne 1 ];thenecho Usage: $0 username    exit 1 fi     echo $1

 

Note: Execute the statement block. If it is empty, use the empty command ":", that is, colon provided by shell. This command does not do anything. Only one exit status 0 is returned. (In shell, 0 is returned, and 1 is returned)

Case statement:

 

#!/bin/bashcase $1 in A)     echo this is A    ;;B|b)    echo this is B or b    ;;*)    echo others    ;;esac

For statement:

Loop Execution Process: when executing the first loop, assign the first word in the list to the loop variable, delete the word from the list, and then enter the loop body, execute the command between do and done. When the next entry enters the loop body, the second word is assigned to the loop variable, the word is deleted from the list, and the column is pushed in sequence. When all the items in the list are removed, the loop ends.

 

You can use $ *, "$ *", $ @, and "$ @" to omit the in list parameter. in this case, use "$ @"

You can also use the following format:

 

for((exp1;exp2;exp3))do...done
Print character triangle:

 

 

#!/bin/bashif [ $# -ne 1 ];then          echo 'usage:$0 
 
   '         exit 1fiif [ $1 -lt "5" -o $1 -gt "15" ];then         echo 'usage : $0 
  
    '         echo '  where 5<=n<=15'         exit 1fifor((i=0;i<$1;i++))do     for((j=0;j<$[$1-$i-1];j++))     do         echo -n " "     done          for((j=0;j<$[2*$i+1];j++))     do         echo -n "*"     done     echo -ne '\n'done
  
 

While statement:

Until statement:

Select list:

Select is an infinite loop. Therefore, remember to use the break command to exit the loop or use the exit command to terminate the script. You can also press ctrl + c to exit the loop. In addition, select is often used together with case. You can also omit the in list. in this case, the location parameter is used.

#!/bin/bashPS3="favorite pet?"select var in Dogs Cats Birdsdo  case $var in   Dogs)       echo Dogs are my favorite pet       break       ;;   Cats)       echo Cats are my favorite pet       ;;   Birds)       echo Birds are my favorite pet       ;;   *)       echo none of my favorite pet       ;;  esac  breakdone

Common String Matching:

 

 

Shift command

It is generally used for processing function or script program parameters. When there are more than 10 parameters, move all parameter variables down to a position where $2 is changed to $1 and $3 to $2, in turn, but $0 remains unchanged.

Interesting example:

 

#!/bin/bashwhile [ “$1” != “” ]do  echo $*  shiftdone

 

(5) Capture signals and Processing

Lock screen program:

 

#!/bin/bashtrap "nice_try" 2 3 15TTY=`tty`nice_try(){    echo -e "\nNice try,the terminal stays locked"}stty -echoecho -n "Enter your pasword to lock $TTY:"read PASSWORDclearecho -n "Enter your password to unlocked $TTY:"while :do     read RESPONSE     if [ "$RESPONSE" = "$PASSWORD" ];then         echo "unlocking ..."         break    fi    clear    echo "wrong password and terminal is locked ..."    echo -n "Enter your password to unlock $TTY:"done stty echo 
Stty-echo is set to not echo.

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.