Shell programming notes (basic)

Source: Internet
Author: User
Tags case statement

1. Variables

A. When you need to assign a value to a variable, you can write it like this:

B. To use the value of a variable, you only need to add a $ (Note: When assigning values to variables, you cannot leave spaces on both sides of "= ".)

C. Then execute chmod + X first to make it executable, and finally input the./file name to execute the script.

#! /Bin/bash # assign a value to the variable: A = "Hello World" # No space exists on both sides of the equal sign # print the value of variable A: Echo "A is:" $

If the variable and string are mixed, follow this method

num=2echo "this is the ${num}nd"

Pay attention to the shellThe default value is a string value.

Var = 1var = $ var + 1 echo $ var # The result is 1 + 1, not 2

The following methods are recommended:

Let "Var + = 1" # method 1var = "$ [$ var + 1]" # method 2 (VAR ++ )) # method 3var =$ ($ var + 1) # Method 4 Note: The first two methods are valid in bash and errors will occur in Sh.

2. If sentence

if ....; then  ....elif ....; then  ....else  ....fi

  

In most cases, you can use test commands to test conditions, such as comparing strings, determining whether a file exists, and whether the file is readable ...... Generally, "[]" is used to represent the conditional test. Note that spaces here are very important,

Make sure that there are spaces before and after square brackets.

[-F "somefile"]: determines whether it is a file.
[-X "/bin/ls"]: determines whether/bin/ls exists and has the executable permission.
[-N "$ Var"]: determines whether the $ var variable has a value.
["$ A" = "$ B"]: determines whether $ A and $ B are equal.
For example:
#!/bin/bashif [ ${SHELL} = "/bin/bash" ]; then   echo "your login shell is the bash (bourne again shell)"else   echo "your login shell is not bash but ${SHELL}"fi

The variable $ shell contains the name of the logon shell. We can compare it with/bin/Bash to determine whether the current shell is Bash.

3. & | Operator

#!/bin/bashmailfolder=/var/spool/mail/james[ -r "$mailfolder" ] || { echo "Can not read $mailfolder" ; exit 1; }echo "$mailfolder has mail from:"grep "^From " $mailfolder

  

This script first checks whether mailfolder is readable. If it is readable, it prints a line of "from" in the file. If it is not readable or the operation takes effect, print the error message and exit the script. Note that the following two commands must be used:

-Print the error message.
-Exit the program.

We use curly braces to put the two commands together as one command in the form of an anonymous function. The common function will be explained later. We can use the if expression to accomplish anything without the use of and or operators, but the use of and or operators is much more convenient.

4. Case statement

case ... in   ...) do something here    ;;esac

For example, create a smartzip script that automatically decompress Bzip2, Gzip, and zip files.

#!/bin/bash ftype="$(file "$1")" case "$ftype" in "$1: Zip archive"*)    unzip "$1" ;; "$1: gzip compressed"*)    gunzip "$1" ;; "$1: bzip2 compressed"*)    bunzip2 "$1" ;; *) echo "File $1 can not be uncompressed with smartzip";; esac

You may notice that a special variable $1 is used above, which contains the first parameter value passed to the script. That is, when we run:

smartzip articles.zip

$1 is the string articles.zip.

5. SELECT statement

select var in ... ; do break;done.... now $var can be used ....

For example:

#!/bin/bashecho "What is your favourite OS?"select var in "Linux" "Gnu Hurd" "Free BSD" "Other"; do  break;doneecho "You have selected $var"

The script runs as follows:

What is your favourite OS?1) Linux2) Gnu Hurd3) Free BSD4) Other#? 1You have selected Linux

6. While/For Loop

while ...; do   ....done

  

As long as the test expression condition is true, the while loop will continue to run. The keyword "break" is used to jump out of the loop, while the keyword "continue" can skip the rest of the loop and directly jump to the next loop.

The for loop will view a string list (strings are separated by spaces) and assign it to a variable:

for var in ....; do   ....done

The following example prints a B c to the screen:

#!/bin/bashfor var in A B C ; do   echo "var is $var"done

The following is a practical script showrpm. Its function is to print the statistics of some RPM packages:

#!/bin/bash# list a content summary of a number of RPM packages# USAGE: showrpm rpmfile1 rpmfile2 ...# EXAMPLE: showrpm /cdrom/RedHat/RPMS/*.rpmfor rpmpackage in "[email protected]"; do   if [ -r "$rpmpackage" ];then      echo "=============== $rpmpackage =============="      rpm -qi -p $rpmpackage   else      echo "ERROR: cannot read file $rpmpackage"   fidone

The second special variable appears.[Email protected]. This variable contains all input command line parameter values.. If you run showrpm OpenSSH. RPM w3m. RPM webgrep. rpm"[Email protected]" (with quotation marks)It contains three strings: OpenSSH. rpm, w3m. rpm, and webgrep. rpm. $ * Means similar. But there is only one string. If no quotation marks are added, parameters with spaces are truncated.

7. Some special symbols in Shell

Before passing any parameters to a program, the program extends the wildcards and variables. Here, the so-called extension means that the program will replace the wildcard (for example, *) with the appropriate file name, and replace the variable with the variable value. We can use quotation marks to prevent this extension. Let's look at an example. Suppose there are two JPG files in the current directory: mail.jpgand tux.jpg.

  • Single quotation marks are not allowed in single quotation marks (not after single quotation marks are used as escape characters)
#!/bin/bashecho *.jpg

  

The running result is:

mail.jpg tux.jpg

Quotation marks (single quotation marks and double quotation marks) can prevent wildcard * extension:

#!/bin/bashecho "*.jpg"echo ‘*.jpg‘

The running result is:

*.jpg*.jpg

The single quotation marks are more strict, which can prevent any variable extension. The double quotation marks can prevent wildcard extension but allow variable extension:

#!/bin/bashecho $SHELLecho "$SHELL"echo ‘$SHELL‘

The running result is:

/bin/bash/bin/bash$SHELL

In addition, there is a method to prevent this extension, that is, to use the Escape Character -- backslice bar :\:

echo \*.jpgecho \$SHELL

Output result:

*.jpg$SHELL

8. Here document

When you want to pass several lines of text to a command, using here document is a good method. It is very useful to write a helpful text for each script. If you use here document, you do not need to use the echo function to output a row. Here document starts with <, followed by a string, which must also appear at the end of the here document. In this example, we rename multiple files and use the here document to print help:

#! /Bin/bash # We have less than 3 arguments. print the help text: If [$ #-lt 3]; thencat 

The first if expression determines whether the input command line parameters are smaller than three (Special variable $ # indicates the number of included Parameters). If the number of input parameters is less than three, the help text is passed to the cat command and then printed on the screen by the cat command. Print the help text and exit the program. If the input parameter is equal to or greater than three, we assign the first parameter to the variable old, and the second parameter to the variable new. Next, we use the shift command to delete the first and second parameters from the parameter list, so that the original third parameter becomes the first parameter in the parameter list $. Then we start the loop. The command line parameter list is assigned to the variable $ file one by one. Then we determine whether the file exists. If yes, we use the SED command to search for and replace the file to generate a new file name. Then, assign the command result in the backslash to newfile. In this way, the old and new file names are obtained. Use the MV command to rename the file.

9. Functions in Shell

functionname(){# inside the body $1 is the first argument given to the function# $2 the second ...body}

The following is a script named xtitlebar, which can change the terminal window name. Here we use a function named help, which is used twice in the script:

#! /Bin/bashhelp () {cat # Determine whether the variable $1 is a Null String. If yes, the return value is true.
[ "$1" = "-h" ] && help
# send the escape sequence to change the xterm titelbar:
echo -e "\033]0;$1\007"
#

It is a good programming habit to help other users (and themselves) use and understand scripts.

String operation concatenation string
your_name="qinjx"greeting="hello, "$your_name" !"greeting_1="hello, ${your_name} !"echo $greeting $greeting_1
Obtain the string length:
String = "ABCD" Echo $ {# string} # output: 4
Extract substring
String = "Alibaba is a great company" Echo $ {string: 1: 4} # output: LIBA
Search for substrings
String = "Alibaba is a great company" Echo 'expr Index "$ string" is '# output: 8. This statement indicates finding the position of the word is in this statement.


You can use the source and. keywords, such:

source ./function.sh. ./function.sh

In bash, source and. they are all reading functions. SH Content and execute its content (similar to include in PHP). For better portability, the second method is recommended.

Like executing a file, a file path must also be written. The file name cannot be written simply. For example:

. ./function.sh

Cannot write:

. function.sh

If function. Sh is a user-passed parameter, how can we obtain its absolute path? The method is:

Real_path = 'readlink-F $ 1' #$1 is a user input parameter, such as function. Sh. $ real_path

 

Shell programming notes (basic)

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.