BASH learning notes

Source: Internet
Author: User
Tags binary to decimal chop echo command

1. Linux script compiling Basics

1.1 Basic syntax Introduction

Start with 1.1.1

The program must start with the following line (must begin with the first line of the file ):

#! /Bin/sh

Symbol #! The parameter used to tell the system that the program is used to execute the file. In this example, we use/bin/sh to execute the program.

When editing a script, you must make it executable if you want to execute it.

To make the script executable:

Compile chmod + x filename to run it with./filename.

1.1.2 notes

During shell programming, a sentence starting with # represents a comment until the end of this line. We sincerely recommend that you use annotations in your program. If you have used annotations, you can understand the role and working principle of the script in a short time even if the script is not used for a long time.

1.1.3 Variables

You must use variables in other programming languages. In shell programming, all variables are composed of strings, and you do not need to declare variables. To assign a value to a variable, you can write as follows:

#! /Bin/sh

# Assign values to variables: Note that there should be no space on both sides of the equal sign

A = "hello world"

# Print the content of variable:

Echo "A is :"

Echo $

Sometimes the variable name is easily confused with other words, such:

Num = 2

Echo "this is the $ numnd"

This does not print "this is the 2nd", but only prints "this is the", because shell will search for the value of the variable numnd, but there is no value for this variable. We can use curly braces to tell shell that we want to print the num variable:

Num = 2

Echo "this is the $ {num} nd"

# This will print: this is the 2nd. variable definitions in BASH are not required. There is no definition process like "int I. If you want to use a variable, it can be used directly as long as it has not been previously defined. Of course, the first statement you use this variable should assign an initial value to him, it does not matter if you do not assign an initial value, but the variable is NULL (Note: It is NULL, not 0 ). The difference between braces and double quotation marks is that double quotation marks cannot be expanded. Double quotation marks cannot prevent variable extension, but can only prevent wildcard * extension.

Note the following when using variables:
1. When a variable is assigned a value, no space is allowed between the left and right sides of "=;
2. The end of a BASH statement does not require a semicolon (";");
3. Except FOR variable assignment and in the FOR loop statement header, the variable in BASH must be preceded by the "$" symbol.

In more detailed bash documents, it is stipulated that variables should be used in the form of $ {STR}. If your script has an inexplicable error, check whether this problem is caused.

Since the variables in BASH do not need to be defined, there is no type. Can a variable store both integers and strings? Yes!
A variable can be defined as a string or an integer. If an integer operation is performed on the variable, it is interpreted as an integer. If a string operation is performed on the variable, it is viewed as a string. See the following example:

#! /Bin/bash
X = 2006
Let "x = $ x + 1"
Echo $ x
X = "a string ."
Echo $ x

Run the following command? A New Keyword: let appears. There are several types of integer variable calculation: "+-*/%", which means the same as the word surface. A backslash must be added before * And, it has been prevented from being explained by SHELL first. Integer operations are generally implemented through the let and expr commands. For example, you can write the variable x by adding 1: let "x = $ x + 1" or x = 'expr $ x + 1'

For runtime parameters, we sometimes want to input parameters when executing the script, such as: # sh mysh. sh hdz (Press ENTER). It is very simple. In bash, the "$" symbol should also be added before the variables passed in.

$ # Number of command line parameters for the input script;

$ * All command line parameter values, with spaces between each parameter value;

Location variable

$0 command itself (shell file name)

$1 The first command line parameter;

$2 the second command line parameter;

...

OK. Edit the following script:
#! /Bin/sh

Echo "number of vars:" $ #

Echo "values of vars:" $ *

Echo "value of var1:" $1
Echo "value of var2:" $2
Echo "value of var3:" $3
Echo "value of var4:" $4

Save the file name as my. sh, and input the following parameter during execution: # sh my. sh a B c d e (Press ENTER). Then you can see the result to better understand the meaning of each variable. If the accessed parameter is not passed in during execution, such code:
Echo & quot; value of var4: & quot; $100

If no 100 parameters are input during execution, the obtained value is NULL.

If a variable is used in a BASH program, the variable remains valid until the end of the program. To make a variable exist in a local program block, the concept of local variables is introduced. In BASH, a local variable can be declared by adding the local keyword when the variable is assigned the initial value for the first time, as shown in the following example:

#! /Bin/bash
HELLO = "var1"
Echo $ HELLO
Function hello {
Local HELLO = "var2"
Echo $ HELLO
}

Echo $ HELLO

The execution result of this program is:

Var1
Var2
Var1

The execution result indicates that the value of the global variable $ HELLO is not changed when the function hello is executed. That is to say, the effect of the local variable $ HELLO only exists in the function block.

Differences between BASH variables and C Variables
Here, programmers who are not familiar with BASH programming but are very familiar with the C language summarize the issues that need to be paid attention to when using variables in the BASH environment.

1. When referencing a variable in BASH, you must add the "$" symbol before the variable (the first value assignment and the "$" symbol is not required in the For loop header );
2. There is no floating point operation in BASH, so there is no variable of the floating point type available;
3. The comparison symbols of Integer Variables in BASH are completely different from those in C language, and the arithmetic operations of integer variables must also be processed by let or expr statements;

1.1.4 Environment Variables

Variables processed by the export keyword are called environment variables. We will not discuss environment variables, because generally, only environment variables are used in the login script.

1.1.5 Shell command and Process Control

Three types of commands can be used in shell scripts:

1) Unix command:

Although any unix command can be used in shell scripts, some more common commands are used. These commands are usually used for file and text operations.

Common command syntax and functions

Echo "some text": print the text on the screen

Ls: file list

Wc-l file; wc-w file; wc-c file: calculate the number of file lines. Calculate the number of words in the file. Calculate the number of characters in the file.

Cp sourcefile destfile: file copy

Mv oldname newname: rename a file or move a file

Rm file: delete an object

Grep 'pattern' file: searches for strings in a file, for example, grep 'searchstring' file.txt.

Cut-B colnum file: specify the content range of the file to be displayed, and output them to the standard output device, for example, output. cut-b5-9 file.txt, 5th to 9th characters per line, should never be confused with cat commands, which are two completely different commands

Cat file.txt: output file content to the standard output device (screen)

File somefile: get the file type

Read var: prompt the user to input and assign the input value to the variable.

Sort file.txt: sorts the rows in the file.txt file.

Uniq: Delete the columns in a text file, for example, sort file.txt | uniq

"|" Is the pipeline descriptor. For more information, see the following section.

Expr: perform mathematical operations Example: add 2 and 3 expr 2 "+" 3

Find: search for a file. For example, search for find.-name filename-print based on the file name.

Tee: outputs data to the standard output device (screen) and files such as: somecommand | tee outfile

Basename file: returns a file name that does not contain a path, for example, basename/bin/tux.

Dirname file: the path of the returned file. For example, dirname/bin/tux will return/bin.

Head file: prints the first few lines of a text file.

Tail file: number of rows at the end of a text file

Sed: Sed is a basic search replacement program. You can read text from standard input (such as command pipeline) and output the results to standard output (screen ). This command uses a regular expression (see references) for search.

Do not confuse with wildcards in shell. For example, replace linuxfocus with LinuxFocus:

Cat text. file | sed's/linuxfocus/LinuxFocus/'> newtext. file

Awk: awk is used to extract fields from text files. By default, the field delimiter is a space. You can use-F to specify other separators.

Cat file.txt | awk-F, '{print $1 "," $3 }'

Here we use it as a field delimiter and print the first and third fields at the same time. If the file contains the following content: Adam Bor, 34, IndiaKerry Miller, 22, and USA, the output result is Adam Bor, IndiaKerry Miller, USA.

2) concept: pipelines, redirection, and backtick

These are not system commands, but they are really important. The pipeline (|) uses the output of a command as the input of another command.

Grep "hello" file.txt | wc-l

Search for a row containing "hello" in file.txt and calculate the number of rows. Here, the grep command output serves as the wc command input. Of course, you can use multiple commands.

Redirection: output the command result to a file instead of a standard output (screen ).

> Write the file and overwrite the old file

> Add it to the end of the file to retain the content of the old file.

''You can use the backslash to output a command as a command line parameter for another command.

Command:

Find.-mtime-1-type f-print

Used to search for files modified in the past 24 hours (-mtime-2 indicates the past 48 hours. If you want to pack all the searched files, you can use the following script:

#! /Bin/sh

# The ticks are backticks (') not normal quotes ('):

Tar-zcvf lastmod.tar.gz 'Find.-mtime-1-type f-print'

3) Process Control

1. if

If the expression "if" is true, the part after then is executed:

If...; then

....

Elif...; then

....

Else

....

Fi

In most cases, you can use test commands to test the conditions. For example, you can compare strings and determine files.

Whether it exists and whether it is readable...

"[]" Is usually used to represent a conditional test. Note that spaces are important. Make sure that the square brackets have spaces.

[-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.

BASH is the Shell of the Linux operating system. Therefore, the system file must be an important object to be operated by BASH.
Operator. The following describes the operations on files: Meaning (TRUE is returned if the following requirements are met)

-E file already exists
-F files are common files.
-S file size is not zero
-D file is a directory
-The r file can be read by the current user.
-W files can be written to the current user
-The x file can be executed on the current user.
-The GID flag of the g file is set.
-Ufile UID flag is set
-O files belong to the current user
The Group ID of the-G file is the same as that of the current user.
File1-nt file2 file file1 is updated than file2
File1-ot file2 file file1 is older than file2
For example, if [-x/root] can be used to determine whether the/root directory can be accessed by the current user.
Run man test to view all types of test expressions that can be compared and judged.

Next let's take a look at the comparison operations between variables: In comparison operations, Integer Variables and string variables are different, see the table below:

Corresponding operation Integer Operation string operation
Same-eq =
Different-ne! =
Greater than-gt>
Less than-lt <
Greater than or equal to-ge
Less than or equal to-le
Blank-z
Not empty-n
For example:
If the integers a and B are equal, write if [$ a = $ B].
To determine whether integer a is greater than integer B, write if [$ a-gt $ B].
Compare whether the strings a and B are equal to write: if [$ a = $ B]
To judge whether string a is null, write: if [-z $ a]
To determine whether integer a is greater than B, write: if [$ a-gt $ B]
Note: There are spaces on the left and right sides of the "[" and "]" symbols.

Directly execute the following script:

#! /Bin/sh

If ["$ 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 compared it with/bin/bash.

Shortcut Operators

If you are familiar with the C language, you may like the following expressions:

[-F "/etc/shadow"] & echo "This computer uses shadow passwors"

Here & is a shortcut operator. If the expression on the left is true, execute the Statement on the right.

You can also think of it as a logical operation. In the preceding example, if the/etc/shadow file exists

Print "This computer uses shadow passwors ". Similarly, the operation (|) is also used in shell programming.

Available. Here is an example:

#! /Bin/sh

Mailfolder =/var/spool/mail/james

[-R "$ mailfolder"] | {echo "Can not read $ mailfolder"; exit 1 ;}

Echo "$ mailfolder has mail from :"

Grep "^ From" $ mailfolder

The script first checks whether mailfolder is readable. If it is readable, the "From" line in the file is printed. If it is not readable or the operation takes effect, print the error message and exit the script. There is a problem here, that is, we must have two commands:

-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. General functions will be mentioned below. We can use the if expression to do anything without the sum or operator, but it is much more convenient to use the sum or operator.

2. case

Case: The expression can be used to match a given string, not a number.

Case "$ var" in
Condition1)

Condition2)

*)
Default statments ;;
Esac

The following example uses the case structure for Branch execution:

#! /Bin/bash

Echo "Hit a key, then hit return ."
Read Keypress

Case "$ Keypress" in
[A-z]) echo "Lowercase letter ";;
[A-Z]) echo "Uppercase letter ";;
[0-9]) echo "Digit ";;
*) Echo "Punctuation, whitespace, or other ";;
Esac

Exit 0

The read Statement in the fourth row of "read Keypress" in the preceding example indicates that the input is read from the keyboard. This command will be explained in other advanced issues of BASH in this handout.

Break/continue
Anyone familiar with C programming is familiar with break statements and continue statements. BASH also has these two statements, and their functions and usage are the same as those in C. The break statement can completely jump out of the current loop body, the continue statement can skip the remaining part of the current loop and directly enter the next loop.

Let's look at another example. The file command can identify the file type of a given file, for example:

File lf.gz

This will return:

Lf.gz: gzip compressed data, deflated, original filename,

Last modified: Mon Aug 27 23:09:18 2001, OS: Unix

We use this to write a script named smartzip, which can automatically decompress bzip2, gzip, and zip compressed files:

#! /Bin/sh

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 we use a special variable $1 here. The variable contains the first parameter value passed to the program. That is to say, when we run: smartzip articles.zip, $1 is the string articles.zip

3. selsect

The select expression is a bash extension application, especially for interactive use. You can select from a group of different values.

Select var in...; do

Break

Done

... Now $ var can be used ....

The following is an example:

#! /Bin/sh

Echo "What is your favorite OS? "

Select var in "Linux" "Gnu Hurd" "Free BSD" "Other"; do

Break

Done

Echo "You have selected $ var"

The following is the result of running the script:

What is your favorite OS?

1) Linux

2) Gnu Hurd

3) Free BSD

4) Other

#? 1

You have selected Linux

4. loop

Loop expression:

While...; do

....

Done

While-loop will run until the expression test is true. Will run while the expression that we test for is true. the keyword "break" is used to jump out of the loop. The keyword "continue" is used to directly jump to the next loop without executing the remaining part.

The for-loop expression is used to view a string list (strings are separated by spaces) and then assigned to a variable:

For var in...; do

....

Done

In the following example, ABC is printed to the screen:

#! /Bin/sh

For var in a B C; do

Echo "var is $ var"

Done

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

#! /Bin/sh

# List a content summary of a number of RPM packages

# USAGE: showrpm rpmfile1 rpmfile2...

# EXAMPLE: showrpm/cdrom/RedHat/RPMS/*. rpm

For rpmpackage in $ *; do

If [-r "$ rpmpackage"]; then

Echo "=====================$ rpmpackage ===================="

Rpm-qi-p $ rpmpackage

Else

Echo "ERROR: cannot read file $ rpmpackage"

Fi

Done

The second special variable $ * is displayed, which contains all input command line parameter values. If you run showrpm openssh. rpm w3m. rpm webgrep. rpm, $ * contains three strings: openssh. rpm, w3m. rpm, and webgrep. rpm.

The for loop structure is different from the C language. In BASH, the basic structure of the for Loop is:

For $ var in [list]
Do
# Code block
Done

Where $ var is a loop control variable, and [list] is a set that var needs to traverse. The do/done pair contains the loop body, which is equivalent to a pair of braces in C. In addition, if do and for are written in the same line, you must add ";" before do ";". For example, for $ var in [list]; do. The following is an example of loop using:

#! /Bin/bash

For day in Sun Mon Tue Wed Thu Fri Sat
Do
Echo $ day
Done

# If the list is contained in a pair of double quotation marks, it is considered an element.
For day in "Sun Mon Tue Wed Thu Fri Sat"
Do
Echo $ day
Done

Exit 0

Note that in the preceding example, the variable day in the row where the for is located does not contain the "$" symbol, but is in the loop body, the line variable $ day in which echo is located must contain the "$" symbol. In addition, if it is written as for day without the subsequent in [list], day will retrieve all the parameters of the command line. Such as this program:

#! /Bin/bash

For param
Do
Echo $ param
Done

Exit 0

The above program will list all command line parameters. The loop body of the for loop structure is contained in the do/done pair, which is also characteristic of the while and until loops.

The basic structure of the while loop is:

While [condition]
Do
# Code block
Done

Compile an example to verify this structure.

The basic structure of the until loop is:

Until [condition is TRUE]
Do
# Code block
Done

You can write an example to verify this structure.

5. quotation marks

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

1.2 compile SHELL scripts

# Ch #! /Bin/sh mod + x filename

Echo *. jpg

Done

Use./filename to execute your script. This will print the result of "mail.jpg tux.jpg. Quotation marks (single quotation marks and double quotation marks) will prevent such wildcard extension:

#! /Bin/sh

Echo "*. jpg"

Echo '*. jpg'

This will print "*. jpg" twice.

Single quotes are stricter. It can prevent any variable extension. Double quotation marks can prevent wildcard extension but allow variable extension.

#! /Bin/sh

Echo $ SHELL

Echo "$ SHELL"

Echo '$ shell'

The running result is:

/Bin/bash

/Bin/bash

$ SHELL

Finally, there is also a method to prevent this extension, that is, to use the Escape Character -- reverse oblique ROD:

Echo \ *. jpg

Echo \ $ SHELL:

*. Jpg

$ SHELL

6. Here documents

To pass several lines of text to a command, here documents is a good method. It is very useful to write a helpful text for each script. If we have the here documents

You do not need to use the echo function to output a row. A "Here document" uses shift by 2

--) Shift; break; # end of options

-*) Echo "error: no such option $1.-h for help"; exit 1 ;;

*) Break ;;

Esac

Done

Echo "opt_f is $ opt_f"

Echo "opt_l is $ opt_l"

Echo "first arg is $1"

Echo "2nd arg is $2"

You can run the script as follows:

Extends parser-l hello-f ---somefile1 somefile2

The returned result is:

Opt_f is 1

Opt_l is hello

First arg is-somefile1

2nd arg is somefile2

How does this script work? The script first loops through all input command line parameters.

Compare with the case expression. If the expression matches, set a variable and remove this parameter. According to the Convention of the unix system, the first input should be the parameter containing the minus sign.

Part 1 instances

Now let's discuss the general steps for writing a script. Any excellent script should have help and input parameters. And write a pseudo script (framework. sh) that contains the framework structure required by most scripts, which is a very good idea. At this time, when writing a new script, we only need to execute the copy command:

Cp framework. sh myscript

Then insert your own function. Let's look at two more examples:

For binary to decimal conversion, the script b2d converts the binary number (such as 1101) to the corresponding decimal number. This is also an example of a mathematical operation using the expr command:

#! /Bin/sh

# Vim: set sw = 4 ts = 4 et:

Help ()

{

Cat <

B2h -- convert binary to decimal

USAGE: b2h [-h] binarynum

OPTIONS:-h help text

EXAMPLE: b2h 111010

Will return 58

HELP

Exit 0

}

Error ()

{

# Print an error and exit

Echo "$1"

Exit 1

}

Lastchar ()

{

# Return the last character of a string in $ rval

If [-z "$1"]; then

# Empty string

Rval = ""

Return

Fi

# Wc puts some space behind the output this is why we need sed:

Numofchar = 'echo-n "$1" | wc-c | sed's // g''

# Now cut out the last char

Rval = 'echo-n "$1" | cut-B $ numofchar'

}

Chop ()

{

# Remove the last character in string and return it in $ rval

If [-z "$1"]; then

# Empty string

Rval = ""

Return

Fi

# Wc puts some space behind the output this is why we need sed:

Numofchar = 'echo-n "$1" | wc-c | sed's // g''

If ["$ numofchar" = "1"]; then

# Only one char in string

Rval = ""

Return

Fi

Numofcharminus1 = 'expr $ numofchar "-" 1'

# Now cut all but the last char:

Rval = 'echo-n "$1" | cut-B 0-$ {numofcharminus1 }'

}

While [-n "$1"]; do

Case $1 in

-H) help; shift 1; # function help is called

--) Shift; break; # end of options

-*) Error "error: no such option $1.-h for help ";;

*) Break ;;

Esac

Done

# The main program

Sum = 0

Weight = 1

# One arg must be given:

[-Z "$1"] & help

Binnum = "$1"

Binnumorig = "$1"

While [-n "$ binnum"]; do

Lastchar "$ binnum"

If ["$ rval" = "1"]; then

Sum = 'expr "$ weight" "+" "$ sum "'

Fi

# Remove the last position in $ binnum

Chop "$ binnum"

Binnum = "$ rval"

Weight = 'expr "$ weight" "*" 2'

Done

Echo "binary $ binnumorig is decimal $ sum"

The script uses decimal and binary weights (, 16 ,..), for example, binary "10" can be converted to decimal: 0*1 + 1*2 = 2. To obtain a single binary number, we use the lastchar function. This function uses wc-c to calculate the number of characters, and then uses the cut command to retrieve the last character. The Chop function removes the last character.

File loop Program

Maybe you want to save all emails to one of the people in a file, but after a few months

In the future, this file may become so large that the access speed to this file may be slowed down. The following script rotatefile

This problem can be solved. This script can rename the email storage file (assuming outmail) to outmail.1,

For outmail.1, it becomes outmail.2 and so on...

#! /Bin/sh

# Vim: set sw = 4 ts = 4 et:

Ver = "0.1"

Help ()

{

Cat <

Rotatefile -- rotate the file name

USAGE: rotatefile [-h] filename

OPTIONS:-h help text

EXAMPLE: rotatefile out

This will e. g rename out.2 to out.3, out.1 to out.2, out to out.1

And create an empty out-file

The max number is 10

Version $ ver

HELP

Exit 0

}

Error ()

{

Echo "$1"

Exit 1

}

While [-n "$1"]; do

Case $1 in

-H) help; shift 1 ;;

--) Break ;;

-*) Echo "error: no such option $1.-h for help"; exit 1 ;;

*) Break ;;

Esac

Done

# Input check:

If [-z "$1"]; then

Error "ERROR: you must specify a file, use-h for help"

Fi

Filen = "$1"

# Rename any. 1,. 2 etc file:

For n in 9 8 7 6 5 4 3 2 1; do

If [-f "$ filen. $ n"]; then

P = 'expr $ n + 1'

Echo "mv $ filen. $ n $ filen. $ p"

Mv $ filen. $ n $ filen. $ p

Fi

Done

# Rename the original file:

If [-f "$ filen"]; then

Echo "mv $ filen $ filen.1"

Mv $ filen $ filen.1

Fi

Echo touch $ filen

Touch $ filen

How does this script work? After the user provides a file name, we perform a 9-1 loop. File 9 is named 10, file 8 is renamed to 9, and so on. After the loop is completed, we name the original file as file 1 and create an empty file with the same name as the original file.

Debugging

The simplest debugging command is the echo command. You can use echo to print any variable value in any suspected error. This is why most shell Programmers spend 80% of their time debugging programs. The benefit of a Shell program is that it does not need to be re-compiled, and it does not take much time to insert an echo command.

Shell also has a real debugging mode. If an error occurs in the script "strangescript", you can debug it as follows:

Sh-x strangescript

This will execute the script and display the values of all variables.

Shell also has a mode that only checks the syntax without executing the script. It can be used as follows:

Sh-n your_script

This will return all syntax errors.

About the shortcut keys of bash in the console

Ctrl + u Delete All characters before the cursor
Ctrl + d delete a character before the cursor
Ctrl + k Delete All characters after the cursor
Ctrl + h delete a character after the cursor
Ctrl + t change the order of the first two characters of the cursor
Ctrl + a move the cursor to the front
Ctrl + e move the cursor to the end
Ctrl + p command
Ctrl + n next command
Ctrl + s lock Input
Ctrl + q unlock
Ctrl + f move the cursor to the next character
Ctrl + B move the cursor to the previous character
Ctrl + x mark a location
Ctrl + c clear the current input

Basic Theoretical Basis
Here there are three file redirection definitions: stdin (standard input), stdout (standard output) andstderr (standard error output) (std = standard ).
Basically, you can
1. Redirect stdout to a file
2. Redirect stderr to a file
3. Redirect stdout to stderr
4. Redirect stderr to stdout
5. Redirect stderr to stdout and become a file
6. Redirect stderrandstdouttostdout
7. Redirect stderrandstdouttostderr
In Linux, 1 indicates the standard output, and 2 indicates the standard error'
Standard output
This example will redirect the ls display result to a file.
Ls-l> ls-l.txt
Standard Error
This example will output the grep Command Errors During running to a file.
Grepda * 2> grep-errors.txt
MPs queue
In this section, we will explain a very simple function that you will definitely use in the future. It is a pipeline.
Why do we all use pipelines?
Pipeline allows you to easily redirect the results of a program to another program.
An example of sed
This example uses a very simple pipeline function:
Ls-l | sed-e "s/[aeio]/u/g"
After we execute the following command: first, ls-l will execute it first and it will output the result information. However, if it is followed by a Pipeline character, then it will redirect the result to the sed program. sed uses the replacement function, all English Words Containing aeio in ls-l results are replaced with the word u.
Use another method to implement ls-l *. txt
This method may be different from ls-l *. txt, But it avoids NoSuchfileOrDirectory.
Ls-l | grep ". txt"
After the ls-lcommand is executed, the program result is output to the grep program and matched with the. txt file.

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.