Bash Programming Summary

Source: Internet
Author: User
Tags case statement define local

Bash should be the most popular shell scripting interpreter on Linux today (and a shell called dash, I hate this stuff too much.) As long as you work on Linux and want to work more happily, you should be familiar with the most basic bash programming, because it will give you enough happiness to work. This article will summarize some of my own usual bash basic programming knowledge, and share with you, but also facilitate their own query.

Variable

1. Bash's variable name is case-sensitive, and the first character of the variable name cannot be a number. Look at the various code also a lot of, to tell the truth, I really did not see whose code with the number of the beginning of the variable name, I think that even if the language allows, there are few people, unless you are really special.

2. Variable Definition and Assignment

Aaa=123

It is important to note that there are no spaces before and after the equals sign when defining variables, and must be written immediately. Although there are spaces after the equals sign, the syntax may not go wrong, but the result is definitely wrong.

3. Variable splicing

Bbb=${aaa}123

Many times, we may need to use a number of variables, constant string, and so on to join a new variable, we need to note that the variables used to splice may need to add {}, otherwise the variable recognition error can be found in the case of a variable. In this case, I tend to have all the variables of a brain full plus {}.

4. Local and export

There are also two commonly used keyword--local and export when defining a variable. Export in the following, define local variables of the local, but I basically do not have, and so I use the time to fill in the summary.

The definition of variables is just that, not to the details of the word, understand that a little bit is enough. If your goal is to become a shell master, then you need professional-level learning, Linux system has a lot of large shell can learn.

Conditional judgment

The IF condition expression involves comparisons of strings , integers , and file attributes .

The IF statement format is:

if [expr]; Then

Do something

Fi

if [expr]; Then

Do something

Else

Do something

Fi

if [expr]; Then

Do something

elif [expr]; Then

Do something

Else

So something

Fi

The IF statement differs from other languages (C,java) in that it is a different line but in a likeness. Then the key can be another row, so that the semicolon after the conditional expression can be omitted. The most important thing to note here is that "[" and "]" must be separated by at least one space before and after.

1. Integer comparison

The integer size comparisons involve operators ——-LT,-le,-eq,-GT,-ge, and-ne.

Example:

A=1
b=2

If [$a-lt $b]; Then
echo "A < B"
Else
echo "a >= B"
Fi

If [$a-ne 3]; Then
echo "A! = 3"
Else
echo "A = = 3"
Fi


If [1-GT 3]; Then
echo "1 > 3"
Else
echo "1 <= 3"
Fi

When you use an integer size comparison of 6 operators, the two operands involved will be treated as numeric values, not strings, even if you use double quotes to cause the comparison object to be used.

2. String comparison

The string comparison may be used by the operator has--=,! =, >, <,-N, and-Z.

Example:
S1=aaa
s2=bbb

If [$s 1 \< $s 2]; Then
echo "$s 1 < $s 2"
Else
echo "$s 1 >= $s 2"
Fi

if [[$s 1 < $s 2]]; Then
echo "$s 1 < $s 2"
Else
echo "$s 1 >= $s 2"
Fi

if [$s 1 = $s 2]; Then
echo "$s 1 = = $s 2"
Else
echo "$s 1! = $s 2"
Fi

If [-n $s 1]; Then
Echo $s 1
Fi

The > and < two operators used for string size comparisons are special and need to be escaped when writing in [], otherwise [[]] can be used instead of []. Not escaping,> and < will be interpreted as IO redirection operations. Second, the IF statement body cannot be empty and must do at least one thing.

The operator-n is used to determine that the string is not empty, that is, the length is not 0. -Z judgment string is empty, that is, the length is 0.

3. File attribute judgment

File attribute judgments involve more operators, as follows:

-E,-A: File exists

-D: Is the directory

-F: Is file

-R: Readable

-W: Writable

-X: Executable

F1-nt F2:F1 new than F2

F1-ot f2:f1 older than F2

The use of these operators and the string operators are basically consistent, in these operators I most commonly used is the-e and-F, the other used less.

In fact, in addition to these three kinds of commonly used judgments, but also should have the execution of command results of the judgment is also more commonly used, this article will not summarize.

For loop

There are two main types of common for loops

Form One

For e in [list]

Do

Do something

Done

This format is commonly used to iterate through all the elements in a list collection and to handle them. Like what:

1. Traverse all files in a directory

For file in ' ls dir '

Do

Echo $file

Done

2. Traverse a given collection

List= "A b c D E F g"

For E in $list

Do

Echo $e

Done

In the in format when iterating through the collection, it is actually separating the strings according to the whitespace characters, getting each element, the ' ls dir ' and $list in the example above get a string with whitespace characters.

Form Two

for ((i = 0; i < n; i++))

Do

Do something

Done

This type of for is basically the same as the C language, only requires a pair of parentheses, it is more adept at making a certain number of cyclic calculations. Like what:

for ((i = 0; i < ten; i++))

Do

Echo $i

Done

for ((;;))

Do

echo "AAAA"

Done

A For loop without a counter is an implementation of a dead loop, which is consistent with the way C is written, and it really has intimacy.

Mastering this for Loop statement, we can do a lot of things, basically enough for us to play.

While loop

This bird egg, I usually do not use, all need to cycle the place are used for. Here is the reason to enumerate the while loop, is to borrow it to spray a variety of languages in the various while, does while, what until and so on. A cycle has to make a variety of different expressions, which is still golang do the most in place. Grammar too much sugar, one day will be bored to death you. Ha ha.

Case statement

The case statement is equivalent to the switch statement in most languages. This is quite useful in addition to the If-elif feature, which also supports wildcard characters. We look directly at examples.

Example:

Url=www.tmall.com

Case $url in
www.taobao.com) echo 1;;
*.taobao.com) echo 2;;
*.tmall.com) echo 3;;
www.tmall.com) echo 4;;
*) echo 5;;
Esac

In the above example, the conditional branch has not only a constant string, but also a string with wildcards, which is convenient for pattern matching. Secondly, it is important to note that the case language matches each other from the first, and that the output of all the above examples is 3, not 4 of the exact match. I think this is a small regret, it would be more fun to support the exact match first.

Second, it is important to note that the end of each conditional branch must be separated by a double semicolon.

Well, the case language is relatively simple, but very practical.

function function definition

function Hello ()

{

echo "Hello World"

}

The function defines a utility keyword, and the parentheses after the function name are optional.

Function call

A function call without arguments only needs to give the function name OK, the function defined above is called directly with Hello. A function with parameters, simply give the parameter after the function name, such as: Func_name arg1 arg2.

function parameters

When a function call can pass arguments to a function, how do you get those parameters in the body of the function? The acquisition of function parameters is consistent with the acquisition of script parameters, which are obtained by means of $, $, and so on. Like what:

function Add ()
{
N=$1
M=$2
echo $ ((n + m))
}

Call add 1 2, which will output 3.

In a function, several parameters can be passed through the $ #的值来判断函数调用的时候.

The bash function rarely returns a value using return. However, you can call a function like this to get the result of the calculation, such as:

Res= ' Add 1 2 '

The value of the variable res is 3. Note that the above is not a single quotation mark, but a character next to the number 1.

String processing

String processing is almost the most frequent thing in the entire computer world. People who play C are many things that are written in string handlers. People who play Java most of the time do not have to write string handlers themselves, but also basically always call the string processing method. Linux actually has a very powerful tool that allows us to do string processing, and before we know it, each tool seems to look very complex. Here's a simple summary of the string-related stuff you've used.

1, to seek the sub-string

Str=abcdefg

Echo ${str:2:3} will get the BCD, 2 of the expression represents the offset, and 3 represents the length.

2. Find string length

str=123456

echo ${#str}

3. String substitution

${variable/PATTERN/XX} replaces the first match in a variable with XX.

The ${variable//pattern/xx} Replaces all matches in the variable with XX.

Str=aaabbbccc

Echo ${str/aaa/xxx}

Echo ${str/a/x}

There are many tools for dealing with strings, such as: You can use Cut, awk and other programs to split a string, and so on.

Integer arithmetic

Integer operations are generally performed using $ (expr). Like what:

echo $ ((1 + 2))
A=1
echo $ ((A + 2))
echo $ ((a++))
echo $ ((++a))
b=2
echo $ (((((A + B)/2))

You can see that only the calculation expression needs to be plugged into $ (()), and the variables that participate in the calculation do not need the $ symbol. The operators involved in integer operations are: + + 、--、 + 、-、 *,/,%, + =, * * (Power operation); There are not commonly used:<<, >>, ^, &,!, |, ~, these in C language is quite common, the shell used to do these bit operation of the need is too 2b. In addition to these operations, logic:<, >, <=, >=, = =,! =, &&, | | | are also supported.

The $ (expr) expression can only evaluate integers and cannot be used for decimal calculations. If you want to do a decimal calculation, you can do this using the command-line calculator BC on Linux.

Example:

echo "1.5 + 1" | Bc

Code generation

Programmers should be "lazy", "lazy" programmers can create more automation tools. I like to use bash to help me do some automatic generation of code, not all the code can be generated automatically, if that is not necessary for programmers. I think the good program must be extensible, the best extensible program is "completion of the program framework, such as the development of functional requirements of the development phase no longer need to write code too much, just fill in the code", the code can be filled, it must be automatically generated, such program development will form a virtuous cycle. Recently I was very keen to refactor my code and try to get my code to be automatically generated with bash scripts, which would greatly improve my development efficiency.

How to generate code automatically, what kind of code is generated according to their actual situation, there is no way to introduce the specific code generation, can only introduce bash to complete the Code generation tool--cat. People who have used Linux know that cat, which is not explained in detail, only shows a simple bash script output Hello World program.

#!/bin/sh

Cat << END > hello.c
#include <stdio.h>

int main (void)
{
printf ("Hello world\n");
return 0;
}
END

Between Cat and end, you can write your own code as you would in an editor, what it looks like, and what it's like to output to a source file, including formatting such as indentation. Of course, the really meaningful code generation will not be as simple as the Hello World here, and you have to "piece together" the automated code according to your actual situation. This is just a demonstration of using cat to generate a source file. The vast majority of bash programming knowledge is required to automatically generate code that really makes sense and improves your development efficiency.

Source (.) and export

People who use Linux know that the terminal in which we beat the command is actually running in a shell that defines a lot of environment variables, such as Path,home. Then, after I run a bash script at the terminal, the bash script is actually running in a sub-shell process where the terminal's shell is forked out. So why is this child shell able to get environment variables such as path,home? This is because these variables are declared in their parent shell in order to export. The export directive allows variables to be passed into the child shell, which is useful when a bash program calls another bash program.

Export allows variables to be passed to the child shell, but not the child shell variables passed to the parent shell, write here, I think I said this transition sentence is very fart. However, you can use the source command to perform similar functions in bash. For example: We can use source in the terminal to run a bash program, then the variables defined in the program, after the end of the program, still exist. This is because executing a script through source does not fork out a child shell to execute, but executes all the statements in the script directly in the current shell. Speaking of which, I think you would like me, too. Source is equivalent to the include directive in the C language.

When a script is too large, I am keen to modularize it, and then separate the modules out as a separate file, and then execute it through the source command in the main file. If you are as lazy as I am, and too lazy to write the source, you can use the dot number (.) instead of source.

Read file by line

When you are doing text processing, you may need to read the contents of a file one line at a time and then handle it, and bash does this very conveniently.

Example:

While Read line
Do
Echo $line
Done < Txt.log

The example shows a line-by-row reading from the file Txt.log to the variable lines. If your file content is structured, for example: Each row is two columns, and you want to handle each column separately, Bash provides a more friendly way to read the file line by row.

Example:

While read C1 C2

Do

echo $c 1: $c 2

Done

In this case, the first column of the read file is assigned to C1, and the second column is assigned the value to C2. This is a bit ruby,python,go and other excellent language support of the multi-variable assignment flavor.

Formatted output

The most common output in Bash is echo, but echo can't format the output, and in the case of automatic code generation, I think you might need to format the output to make the code more neat and beautiful. C has function printf support formatted output, Linux also has printf tool, let you like C language generally arbitrary output.

Examples of the approximate use of printf:

printf "My name is%s, I am%d years old.\n" Skoo 25

I think the use of Linux printf and C language is very little different, the detailed usage can be man printf go.

Attached: sed and awk

I think sed and awk are two great artifacts, but there are not many people who can really harness them. I'm just superficial knowledge, so I'm not here to talk nonsense. Learning any programming language, to reflect the productivity of the time, are the puzzle. Bash does not have a library function, but it has a rich Linux command, to write a really powerful and meaningful bash program, you have to learn some of the Linux commands, only enough to grasp the Linux command to be able to do. Just like most Java programmers, there are no rich libraries, and they may not be able to do anything meaningful without the knowledge of the grammar. C + + Programmers are no exception, though they are keen to use only a little bit of grammar to reinvent the wheel.

Bash Programming Summary

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.