Bash programming Basics

Source: Internet
Author: User

Bash programming Basics

I. The origin of Bash

1. What is Bash? shell Bash is GNU Bourne-again shell, which is used by most Linux distributions.

Shell is an interface provided by * nix for users. The underlying layer of an operating system runs independently,

The user interface is separated from the underlying layer to maximize system stability. Shell is a special program that accepts user commands and returns system responses to users.

BASH Shell

Generally, you do not need to install it on your own. It is installed at the same time as the release version.

The existence of shell is related to login. After the user name and password are verified, shell starts. If you know that you quit, shell ends.

Running. In addition to bash shell, there are many other shells

650) This. width = 650; "style =" background-image: none; Border: 0px; padding-left: 0px; padding-Right: 0px; padding-top: 0px; width: 400px; height: 254px; "Title =" wps_clip_image-25544 "border =" 0 "alt =" wps_clip_image-25544 "src =" http://img1.51cto.com/attachment/201408/3/8400375_1407046197UG1D.png "Height =" 254 "width =" 400 "hspace =" 0 "vspace =" 0 "/>

You can use variables in any programming language, but they do not have any type in Script Programming, referred to as weak type programming language.

A variable can contain a number, a string, a word, and so on. You do not need to declare this variable. It will reference this variable.

Create it.
Use variables to implement a simple hello World
#! /Bin/bash
STR = "Hello world! "
Echo $ Str

Ii. Bash features-Wildcard file name (globbing ):

650) This. width = 650; "style =" background-image: none; Border: 0px; padding-left: 0px; padding-Right: 0px; padding-top: 0px; width: 400px; height: 208px; "Title =" wps_clip_image-6418 "border =" 0 "alt =" wps_clip_image-6418 "src =" http://img1.51cto.com/attachment/201408/3/8400375_1407046203jp1D.png "Height =" 208 "width =" 400 "hspace =" 0 "vspace =" 0 "/>

*: Any characters of any length, such as P * D, pad, PBD, and Pd * AB * C? : Match any single character []: match any single character in the specified range [ABC], [A-Z], [0-9], [0-9a-z] [^]: match any single character other than the specified range [^ 0-9a-z] Character Set combination: [: Space:]: All blank characters [: punct:]: All Punctuation Marks [: lower:]: all lowercase letters [: Upper:]: all uppercase letters [: digit:]: numbers [: alnum:]: numbers and letters [: Alpha:]: All letters

Iii. Input and Output

>/Dev/null CAT/path/file </somewhere/File

Exercise: write a script

1. Add 10 users: tuser601-tuser610

If the user does not exist, the user is added, and the user is successfully added in green. If the user exists, the user is already added in red;

2. shows the total number of users added;

#!/bin/bash#declare -i count=0for i in {501..510}; doif id tuser$i &> /dev/null; thenecho -e "\033[31mtuser$i\033[0m exists."elseuseradd tuser$iecho -e "add user \033[32mtuser$i\033[0m successfully."let count++  fidoneecho "Total add $count users."

File: File System (kernel)

Standard Input: 0 keyboard standard output: 1 monitor error output: 2 monitor redirection means: change its standard position output redirection: Command> position: overwrite output command> position: append Output Error redirection: Command 2> position: overwrite output command 2> position: append output merge redirection: Command &> positioncommand> position 2> & 1bash important features: Variables

Iv. Bash variable category:

Local variables: Only variables valid for the current shell process; other shell processes are invalid, and the sub-processes of the current shell process are packaged;

Var_name = Value

Variable assignment: saves data to the storage space of the variable.

Variable reference: $ {var_name}

650) This. width = 650; "style =" background-image: none; Border: 0px; padding-left: 0px; padding-Right: 0px; padding-top: 0px; width: 400px; height: 240px; "Title =" wps_clip_image-9798 "border =" 0 "alt =" wps_clip_image-9798 "src =" http://img1.51cto.com/attachment/201408/3/8400375_14070462124aVb.png "Height =" 240 "width =" 400 "hspace =" 0 "vspace =" 0 "/>

"": Weak reference. The variables will be replaced;

'': Strong reference. All the characters in it are literal and can be directly output;

650) This. width = 650; "style =" background-image: none; Border: 0px; padding-left: 0px; padding-Right: 0px; padding-top: 0px; width: 400px; height: 256px; "Title =" wps_clip_image-8925 "border =" 0 "alt =" wps_clip_image-8925 "src =" http://img1.51cto.com/attachment/201408/3/8400375_1407046220QSoW.png "Height =" 256 "width =" 400 "hspace =" 0 "vspace =" 0 "/>

Environment variable: valid for the current shell process and its sub-shell, and invalid for other shell processes; Definition: Export var_name = value export: Export var_nameexport lang = en modify the font, valid only for the current process. User can customize the environment variable Bash. There are many built-in environment variables undo variable: unset var_name read-only variable: readonly var_name local variable: Local

650) This. width = 650; "style =" background-image: none; Border: 0px; padding-left: 0px; padding-Right: 0px; padding-top: 0px; width: 400px; height: 241px; "Title =" wps_clip_image-32302 "border =" 0 "alt =" wps_clip_image-32302 "src =" http://img1.51cto.com/attachment/201408/3/8400375_1407046223HpZb.png "Height =" 241 "width =" 400 "hspace =" 0 "vspace =" 0 "/>

It is valid for a code segment in the shell script; it is usually used for local functions; Local var_name = value location variable: $1, $2,..., $ {10} special variable: $? View all the variables in the Current Shell Process: Set view all the environment variables in the Current Shell Process: Export, Printenv, ENV login type: 5. Execute the order interactive script on the computer: directly enter the account and password to log on through the terminal; Use Su-l username or Su-username; non-interactive: the terminal opened under the su username graphic interface is executed to execute the script and the configuration modified by editing the configuration file takes effect? 1. log out and log on again. 2. Let bash repeat the configuration file ;. filesource file:/etc/profile -->/etc/profile. d /*. sh --> ~ /. Bash_profile --> ~ /. Bashrc -->/etc/bashrc non-interactive Login User :~ /. Bashrc -->/etc/profile. d /*. sh syntax highlight: syntax on | off Search highlight: Set hlsearch: Set nohlsearch configuration file: Global:/etc/vimrc User :~ /. Vimrc

Vi. shell script format:

The first line, the top grid: shebang #! /Bin/bash #! Other lines starting with # in/usr/bin/Python are comments and will be ignored by the interpreter.

Exercise: write a script

1. The script can take more than one file path as the parameter;

2. display the number of rows in each file;

3. displays the total number of rows executed for each file;

Script

650) This. width = 650; "style =" background-image: none; Border: 0px; padding-left: 0px; padding-Right: 0px; padding-top: 0px; width: 400px; height: 184px; "Title =" wps_clip_image-32750 "border =" 0 "alt =" wps_clip_image-32750 "src =" http://img1.51cto.com/attachment/201408/3/8400375_1407046228xegG.png "Height =" 184 "width =" 400 "hspace =" 0 "vspace =" 0 "/>

Execution result

650) This. width = 650; "style =" background-image: none; Border: 0px; padding-left: 0px; padding-Right: 0px; padding-top: 0px; width: 400px; height: 202px; "Title =" wps_clip_image-27338 "border =" 0 "alt =" wps_clip_image-27338 "src =" http://img1.51cto.com/attachment/201408/3/8400375_1407046239pI9t.png "Height =" 202 "width =" 400 "hspace =" 0 "vspace =" 0 "/>

Exercise: write a script

1. display the username in the even row of the file in the/etc/passwd file, and display the total number of such users;

Script

650) This. width = 650; "style =" background-image: none; Border: 0px; padding-left: 0px; padding-Right: 0px; padding-top: 0px; width: 400px; height: 179px; "Title =" wps_clip_image-6223 "border =" 0 "alt =" wps_clip_image-6223 "src =" http://img1.51cto.com/attachment/201408/3/8400375_1407046249Lit5.png "Height =" 179 "width =" 400 "hspace =" 0 "vspace =" 0 "/>

Result

650) This. width = 650; "style =" background-image: none; Border: 0px; padding-left: 0px; padding-Right: 0px; padding-top: 0px; width: 400px; height: 153px; "Title =" wps_clip_image-18979 "border =" 0 "alt =" wps_clip_image-18979 "src =" http://img1.51cto.com/attachment/201408/3/8400375_1407046253o8zR.png "Height =" 153 "width =" 400 "hspace =" 0 "vspace =" 0 "/>

VII. Basics of the Keyword Method in bash

1. numeric test conditions and string Operators

650) This. width = 650; "style =" background-image: none; Border: 0px; padding-left: 0px; padding-Right: 0px; padding-top: 0px; width: 400px; height: 192px; "Title =" wps_clip_image-14189 "border =" 0 "alt =" wps_clip_image-14189 "src =" http://img1.51cto.com/attachment/201408/3/8400375_1407046256RTxr.png "Height =" 192 "width =" 400 "hspace =" 0 "vspace =" 0 "/>

2. String Testing

650) This. width = 650; "style =" background-image: none; Border: 0px; padding-left: 0px; padding-Right: 0px; padding-top: 0px; width: 400px; height: 225px; "Title =" wps_clip_image-4463 "border =" 0 "alt =" wps_clip_image-4463 "src =" http://img1.51cto.com/attachment/201408/3/8400375_14070462639WnQ.png "Height =" 225 "width =" 400 "hspace =" 0 "vspace =" 0 "/>

3. Logic and or operations

-A and-O or! No, & | and the previous execution is complete. If the execution is followed by the previous error, it will not be executed. Combined condition test: Implements logical operations between multiple conditions and: [condition1-A condition2] condition1 & condition2 or: [condition1-O condition2] condition1 | condition2 not: [-not condition]! Condition

650) This. width = 650; "style =" background-image: none; Border: 0px; padding-left: 0px; padding-Right: 0px; padding-top: 0px; width: 400px; height: 272px; "Title =" wps_clip_image-24372 "border =" 0 "alt =" wps_clip_image-24372 "src =" http://img1.51cto.com/attachment/201408/3/8400375_1407046271sROe.png "Height =" 272 "width =" 400 "hspace =" 0 "vspace =" 0 "/>

650) This. width = 650; "style =" background-image: none; Border: 0px; padding-left: 0px; padding-Right: 0px; padding-top: 0px; width: 400px; height: 209px; "Title =" wps_clip_image-24117 "border =" 0 "alt =" wps_clip_image-24117 "src =" http://img1.51cto.com/attachment/201408/3/8400375_1407046276mo4v.png "Height =" 209 "width =" 400 "hspace =" 0 "vspace =" 0 "/>

Exercise: prompt the user to enter a user name. If the user exists, the user's ID and shell are displayed; otherwise, the user is not displayed.

Yes; Do not exit after the display is complete. Repeat the previous operation until the user inputs Q or quit;

 

read -p "Plz enter a username: " userName  while [ "$userName" != ‘q‘ -a "$userName" != ‘quit‘ ]; do  if id $userName &> /dev/null; then      grep "^$userName\>" /etc/passwd | cut -d: -f3,7  else  echo "No such user."  fi  read -p "Plz enter a username again: " userName  Done

Exercise: Calculate the sum of all even numbers within 100. The modulo method is required;

#!/bin/bashdeclare -i counter=1declare -i sum=0while [ $counter -le 100 ]; do    if [ $[$counter%2] -eq 0 ]; then        let sum+=$counter    fi    let counter++doneecho $sum

2. File test:

-E file name: True-r file name if the file exists: True-W file name if the file exists and is readable: True-X file name if the file exists and can be written: true-s file name if the file exists and can be executed: if the file exists with at least one character, it is true-D file name: if the file exists and is a directory, it is true-F File Name: true-C file name if the file exists and is a common file: True-B file name if the file exists and is a special file in bytes: true if the file exists and is a special file in blocks

650) This. width = 650; "style =" background-image: none; Border: 0px; padding-left: 0px; padding-Right: 0px; padding-top: 0px; width: 400px; height: 244px; "Title =" wps_clip_image-30006 "border =" 0 "alt =" wps_clip_image-30006 "src =" http://img1.51cto.com/attachment/201408/3/8400375_1407046287NcER.png "Height =" 244 "width =" 400 "hspace =" 0 "vspace =" 0 "/>

Exercise: write a script to complete the following tasks:

1. Copy files under/var/log to the/tmp/logs/directory respectively. 2. When copying a directory, use CP-R3 or copy a file, use cp4, copy the linked file, use CP-D5, and the remaining types, and use CP-AIF [-d $1]; thencp-r/var/log/$1/tmp/logselif [-d $1]; thencp-r/var/log/$1/tmp/logsif [-F $1]; thencp/var/log/$1/tmp/logselsecp-A/var/log/$1/tmp/logsfi

650) This. width = 650; "style =" background-image: none; Border: 0px; padding-left: 0px; padding-Right: 0px; padding-top: 0px; width: 400px; height: 153px; "Title =" wps_clip_image-19798 "border =" 0 "alt =" wps_clip_image-19798 "src =" http://img1.51cto.com/attachment/201408/3/8400375_1407046295d3Hp.png "Height =" 153 "width =" 400 "hspace =" 0 "vspace =" 0 "/>

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.