Shell Programming Basics-Grammar Quick Start

Source: Internet
Author: User
Tags array definition case statement set background

Simply put, the shell is a file containing several lines of shell or Linux commands. For a large number of commands that are written and used more than once, you can use a separate file to save it for later use. Usually the shell script is suffixed with. SH, and the first line must indicate which shell the system needs to interpret the user's shell program, such as #!/bin/bash, #!/bin/sh, and so on. Here we use the #!/bin/bash.

usually the shell is made up of Linux command (external command), Shell ( internal command) , control statements and comment statements, and so on, are similar to the batch file (. bat) under Windows. It is also important to note that we need to execute shell scripts using chmod +x name.sh.

(i) Variables and arrays

1. Use type to determine if internal command: type cmd

2. If the variable is empty, directly follow + Enter, and there is no space on either side of the equal sign.

3. Echo $a The value of output a

4. Export a, set a to global variable

Displays the value of the variable: Echo $A, {} is used to prevent confusion, such as the value of output A plus the B character: echo${a}b

5. Delete variable: unset A

6. Show all variables (including local): set; Set | grep A (shows a variable); ENV Displays global variables (environment variables); Initializes global variables: Export a=200. In addition to global variables, it is customary to capitalize: Export LANG

Note: Global variables can be accessed by all shell environments , and if the parent Shell Process produces a child shell process, the environment variable can be " inherit " and copy

7. Read-only variables, which are variables that cannot be cleared or re-assigned: readonly MyVar

8. Positional parameters (command line parameters): Positional parameters are a special set of built-in variables, usually used by shell scripts to accept parameters from the command line, or by functions to hold arguments passed to him. Equivalent to the argv in C , where $ $ represents the first argument, and the second ... . $9 to surround the numbers with curly braces, ${10}; $ A represents the file name of the current script.


Test procedure:

#!/bin/bash# Test position parameters and other special parameters # Usage:/target.sh parameter 1  parameter 2ifs= #echo shell script name is: $0echo The count of parameters: $ #ec Ho First Param=$1echo second Param=$2echo ' $*= ' $*      #显示所有的位置参数串echo ' "$*" = "$*" ' echo ' [email protected]= ' [email Protected]echo ' [email protected] "= '" [email protected] "echo ' $$= ' $$      #显示当前进程号echo $!

Array definition and initialization: arr= (math Chinese 中文版)

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

Array Assignment: Arr[0]=chemial

It is important to note that the shell array can be discontinuous, which is also different from other languages, such as: Arr[0], arr[1],arr[2],arr[5] is allowed, their output (if the previous assignment and subscript the same), the array output is 0 1 2 5 , the number is 4.

(ii) input and output


- P representative prompt; - T represents Timeout period ; echo $REPLY; Echo-n indicates no output return; - e "\ t" represents the Escape option

echo Color output and cursor positioning

\33 represents the start of escape, formatted as [ number m, changing color from the beginning of the cursor

\33[30m--\33[37m set foreground color \33[40m--\33[47m Set background color \33[y;xh  Set Cursor Position example: ECHO-E "\33[31mthis" is a test "echo-e" \33[10;5h\33 [31;46mthis is a test "echo-e" \33[0m "

(c) characters and test statements


the expansion of arithmetic, Note: Always leave a space on both ends of the symbol!


Expression test:


String test:



Check for null values

["$name" = ""]

[ ! "$name"]

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

Note: There are spaces on both sides of the string test


can also use (()), but the two are not the same, [] can only and-eq andothersymbols paired , and (()) only and ; <= symbol pairing.


In addition [[Expr1 && EXPR2]] etc. is also possible. (| | )


A simple summary of the test:


(iv) Conditions and circular statements

If statement:


If [$#-ne 1];thenecho Usage: $ username    Exit 1 fi     echo $

Note: The executable block, if empty, needs to use the empty command ":", or colon, provided by the Shell . The command does nothing and returns only one exit status of 0. (Shell returns 0 for successful execution, return 1 for failure)

Case statement:


#!/bin/bashcase $ A) echo this is     A    ;; B|B)    echo this is B or B    ;; *)    echo others    ;; Esac

For statement:

Loop execution: When the first loop is executed, the first exposition in the list is given to the loop variable, and the word is removed from the list and then into the loop body, executing the command between do and done. The next time you enter the loop body, the second exposition is given to the loop variable, and the word is removed from the list, followed by a column push. When all of the list is removed, the loop ends.

Positional parameters using $*, "$*", [email protected], "[email protected]", you can omit the in list, this time using "[email protected]"

You can also use the following form:

For ((EXP1;EXP2;EXP3)) Do...done
To print a character triangle:

#!/bin/bashif [$#-ne 1];then          echo ' usage:$0 <n> '         exit 1fiif [$1-lt ' 5 '-o $1-gt ' "];then         Echo ' Usage: $ <n> '         echo '  where 5<=n<=15 '         exit 1fifor ((i=0;i<$1;i++)) do for     ((j=0;j<$ [$1-$i -1];j++)]     do         echo-n "" Did 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, so remember to exit the loop with the break command, or terminate the script with the Exit command. You can also press CTRL + C to exit the loop. In addition the select is used often in conjunction with case. You can also omit the in list, at which point the positional parameters are used.

#!/bin/bashps3= "Favorite pet?" Select Var in Dogs Cats birdsdo case  $var in   Dogs)       echo Dogs is my favorite pet       break       ;;   Cats)       Echo Cats is my favorite pet       ;;   Birds)       Echo Birds is my favorite pet       ;;   *)       echo none of my favorite pet       ;;  Esac  Breakdone

Common string matches:

Shift Command

Generally used for function or script parameter processing, especially when the parameters more than ten times, all the parameter variables down one position, the $1,$3 into $ , then Progressive, but the $ is unchanged.

An interesting example:

#!/bin/bashwhile [""! = ""]do  echo $*  shiftdone

(v) Capture signal and its 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:d o     read RES Ponse     If ["$RESPONSE" = "$PASSWORD"];then         echo "Unlocking ..." break    fi    clear    echo "wrong Password and terminal is locked ... "    
Stty-echo is not set to echo.









Shell Programming Basics-Grammar Quick Start

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.