BASH Learning notes Summary _linux Shell

Source: Internet
Author: User
Tags binary to decimal chop echo command file copy readable save file uppercase letter vars
1. Linux Scripting Basics

1.1 Basic Introduction to grammar

1.1.1 Start

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

#!/bin/sh

The symbolic #! is used to tell the system that the parameters behind it are the programs used to execute the file. In this example we use/BIN/SH to execute the program.

When you edit a good script, you must also make it executable if you want to execute the script.

To make the script executable:

Compile chmod +x filename so you can use./filename to run

1.1.2 Notes

In shell programming, comments are expressed in sentences that begin with # until the end of the line. We sincerely recommend that you use annotations in your programs. If you use annotations, you can understand how the script works and work in a very short period of time, even if you haven't used it for a very long time.

1.1.3 Variable

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 this:

#!/bin/sh

#对变量赋值: Note that there should be no space on both sides of the equal sign

A= "Hello World"

# now print the contents of variable a:

echo "A is:"

Echo $a

Sometimes variable names can easily be confused with other words, such as:

num=2

echo "This is the $NUMND"

This does not print out "This is the 2nd" and only prints "This is the" because the shell searches for the value of the variable numnd, but the variable has no value. You can use curly braces to tell the shell what we want to print is the NUM variable:

num=2

echo "This is the ${num}nd"

#这将打印: This is the 2nd, the variable definition in BASH is not required, there is no definition procedure such as "int i". If you want to use a variable, as long as he has not been defined in front, it can be used directly, of course, the first sentence you use the variable should be an initial value to him, if you do not assign initial value does not matter, but the variable is empty (note: Is null, not 0). The effect of curly braces, and the difference between double quotes: curly braces, double quotes so that can not be extended, double quotes can not prevent the extension of the variable, can only prevent the extension of the wildcard *, after the text is explained in detail.

For the use of variables, pay attention to the following points:
One, the variable assignment value, "=" Both sides can not have spaces;
Second, the end of the statement in BASH does not require a semicolon (";" );
Third, in addition to the variable assignment and in the For Loop statement header, the variable in BASH must be in front of the variable with the "$" symbol.

In a more detailed bash document, you will be required to use a variable in such a form: ${str}, if your script is out of the question, you might want to see if the problem is caused.

The variables in BASH don't need to be defined, and there's no type. A variable can hold an integer or a string? Right!
A variable can be defined as a string, or it can be redefined as an integer. If you perform an integer operation on the variable, he is interpreted as an integer, and if the string is manipulated, he is treated as a string. Take a look at the following example:

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

Perform a look at it? There is a new keyword: let. As for the calculation of integer variables, there are the following: "+-*/%", they have the same meaning and literal meaning, the * and/before must be preceded by a backslash, has been anti-shell first explanation. Integer operations are generally implemented through the two instructions of let and expr, such as the variable x plus 1 can be written: let "x = $x + 1" or x= ' expr $x + 1 '

With regard to run-time parameters, we sometimes want to pass a parameter in the execution of the script, such as: #sh mysh.sh HDZ (carriage return) good, very simple, in bash, use this to pass in the variable to be preceded by the "$" symbol.

$# the number of command line arguments for incoming scripts;

$* all command line parameter values, leaving spaces between each parameter values;

Position change Element

The $ command itself (shell filename)

The first command-line argument;

$ $ second command-line argument;

...

OK, edit the following script:
#!/bin/sh

echo "Number of VARs:" $#

echo "Values of VARs:" $*

echo "Value of VAR1:" $
echo "Value of VAR2:" $
echo "Value of VAR3:" $
echo "Value of VAR4:" $

Save file name is my.sh, pass in parameter when executing: #sh my.sh a b C d e (carriage return), see the result you will know the meaning of each variable more. If the access parameter is not passed in at execution time, there is one such code:
echo "Value of VAR4:" $

While executing without entering 100 parameters, the value obtained is NULL

If a variable is used in a BASH program, the variable remains in effect until the end of the program. In order 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 when the variable is first assigned an initial value, as in the following example:

#!/bin/bash
hello= "Var1"
Echo $HELLO
function Hello {
Local hello= "Var2"
Echo $HELLO
}

Echo $HELLO

The results of this program are:

Var1
Var2
Var1

This 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 a local variable $HELLO only exists in the function that program block.

The difference between a variable in BASH and a variable in the C language
Here we are working with programmers who are not familiar with bash programming, but are very familiar with C language to summarize the issues that need to be noted in using variables in a bash environment.

A variable in 1,bash needs to precede the variable with a "$" symbol (first assignment and no "$" symbol for the head of the For loop);
There is no floating-point operation in the 2,bash, so there is no floating-point type variable available;
The comparison symbol of the 3,bash is quite different from the C language, and the arithmetic operation of the reshaping variable also needs to be processed by a let or expr statement;

1.1.4 Environment variables

Variables processed by the EXPORT keyword are called environment variables. We do not discuss environment variables because, in general, environment variables are used only in logon scripts.

1.1.5 shell command and Process Control

There are three types of commands that can be used in a shell script:

1 Unix Command:

Although arbitrary UNIX commands can be used in shell scripts, there are some relatively more commonly used commands. These commands are usually used for file and text operations.

Common command syntax and functions

echo "Some text": Print text content on screen

LS: File list

Wc–l file; Wc-w file; Wc-c file: Calculate the number of rows in the calculation file number of characters in the calculation file

CP sourcefile destfile: File copy

MV Oldname newname: Renaming a file or moving a file

RM file: Deleting files

grep ' pattern ' file: Search for strings within a file for example: grep ' searchstring ' file.txt

Cut-b colnum File: Specifies the range of files to display and outputs them to a standard output device such as: Output. 5th to 9th characters per line cut-b5-9 file.txt never confuse with cat commands, which are two completely different commands

Cat file.txt: Output file contents to standard output device (screen)

File somefile: Getting files Type

Read Var: Prompts the user for input and assigns the input to the variable

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

Uniq: Delete the rows that appear in a text file for example: sort file.txt | Uniq

"|" is a pipe descriptor, as detailed in the following article.

Expr: Mathematical operations Example:add 2 and 3expr 2 "+" 3

Find: Search for files such as: Search for Find by filename. -name Filename-print

Tee: Output data to standard output devices (screens) and files such as: Somecommand | Tee outfile

basename file: Returns a filename that does not contain a path such as: Basename/bin/tux will return Tux

DirName file: Returns the path where the files are located for example: Dirname/bin/tux will return/bin

Head file: Print the first few lines of a text file

Tail File: Print a few lines at the end of a text file

Sed:sed is a basic search and replace program. You can read text from standard input, such as a command pipe, and output the results to the standard output (screen). The command searches using a regular expression (see Reference).

Do not confuse with wildcard characters in the shell. For example: Replace the Linuxfocus with Linuxfocus:

Cat Text.file | Sed ' s/linuxfocus/linuxfocus/' > Newtext.file

Awk:awk is used to extract fields from a text file. By default, the field separator is a space, and you can specify additional delimiters using-F.

Cat File.txt | Awk-f, ' {print $ ', ' $} '

Here we use, as a field separator, to print both the first and third fields. If the contents of the file are as follows: Adam Bor, Indiakerry Miller, USA command output is: Adam Bor, Indiakerry Miller, USA

2 Concept: Pipelines, redirects and Backtick

These are not system commands, but they are really important. Pipe (|) The output of one command as input to another command.

grep "Hello" file.txt | Wc–l

Searches the file.txt for a row containing "Hello" and calculates its number of rows. Here the output of the grep command is used as input to the WC command. Of course you can use more than one command.

Redirect: Outputs the results of a command to a file instead of the standard output (screen).

> Write files and overwrite old files

>> add to the end of the file and keep the old file contents.

' Use a backslash to take the output of one command as a command-line argument for another command.

Command:

Find. -mtime-1-type F-print

Used to find files that have been modified in the last 24 hours (-mtime–2 for the last 48 hours). If you want to make a package of all the files you find, 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

An "if" expression executes the part following then if the condition is true:

If ...; Then

....

Elif ...; Then

....

Else

....

Fi

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

Whether it exists and is readable, etc...

You typically use [] to represent a conditional test. Note that the spaces here are important. To ensure that the square brackets are blank.

[f "Somefile"]: To determine whether a file

[-X "/bin/ls"]: Determine if/bin/ls exists and has executable permissions

[-N ' $var]: Determine if the $var variable has a value

["$a" = "$b"]: Determine if $a and $b are equal

Bash is the Shell of the Linux operating system, so the system's files must be an important object that bash needs to manipulate
operator, the following is an action on a file: meaning (returns TRUE if the following requirements are met)

-e file already exists
-F file is a normal file
-S file size is not zero
-d file is a directory
-R file can be read by the current user
-W file can be written to the current user
-x file can be executed for the current user
The GID flag for the-G file is set
The UID flag of the-u file is set
The-o file is owned by the current user
The group ID of the-G file is the same as the current user
file1-nt file2 file file1 newer than file2
File1-ot file2 file file1 older than file2
If [-x/root] can be used to determine whether the/root directory can be entered by the current user
Execute man test to see the types that all test expressions can compare and judge.

Let's look at the comparison between variables: On the comparison operation, the integer variable and the string variable are different, as shown in the following table:

The 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
Is null-Z
Not null-n
Like what:
Compare integers A and b for equality and write if [$a = $b]
To determine if an integer A is greater than integer b, write if [$a-gt $b]
Compare strings A and b for equality on writing: if [$a = $b]
To determine if a string A is empty, write: if [-Z $a]
To judge whether an integer variable A is greater than B, write: If [$a-gt $b]
Note: Spaces are left in the left and right of the "[" and "]" symbols.

Execute the following script directly:

#!/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 login shell, which we compared with/bin/bash.

Shortcut operators

A friend who is familiar with C may like the following expression:

[f "/etc/shadow"] && echo "This computer uses Shadow Passwors"

Here && is a shortcut operator that executes the statement on the right if the expression on the left is true.

You can also think of it as an operation in a logical operation. The example above indicates that if the/etc/shadow file exists

Then print "This computer uses Shadow Passwors". Same OR operation (| |) Also in shell programming.

Available. Here's 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 determines whether the mailfolder is readable. If readable, prints the "from" line in the file. If unreadable or the operation takes effect, the script exits after printing the error message. Here's the problem, which is that we have to have two orders:

-Print error messages

-Exit Program

We use curly braces to put two commands together as a command in the form of anonymous functions. The general functions are mentioned below. Without the and OR operator, we can do anything with an if expression, but it is much more convenient to use the and or operators.

2.case

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

Case "$var" in
Condition1)

Condition2)

* )
Default statments;;
Esac

The following is an example of branching execution using the case structure:

#!/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 line of "read Keypress" in the example above represents reading input from the keyboard. This command will be explained in the other high-level issues of BASH in this handout.

Break/continue
Familiar with C language programming are familiar with break statements and continue statements. BASH also has these two statements, and the role and usage is the same as in the C language, the break statement allows the program flow to jump out of the current loop body, and the continue statement can skip over the remainder of the secondary loop and go straight to the next loop.

Let's look at one more example. The file command can identify a given file type, such as:

File lf.gz

This will return:

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

Last Modified:mon Aug 23:09:18 2001, Os:unix

We use this to write a script called Smartzip, which automatically extracts bzip2, gzip, and zip-type compressed files:

#!/bin/sh

Ftype= ' file '

Case "$ftype" in

"$1:zip Archive" *)

Unzip "$";;

"$1:gzip Compressed" *)

Gunzip "$";;

"$1:bzip2 Compressed" *)

Bunzip2 "$";;

*) echo "File of Can not is uncompressed with smartzip";;

Esac

You may notice that we are using a special variable here. The variable contains the first parameter value passed to the program. In other words, when we run: Smartzip Articles.zip, the $ is a string articles.zip

3. Selsect

A select expression is an extended application of bash and is especially good at interactive use. Users can choose from a different set of values.

Select Var in ...; Todo

Break

Done

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

Here is an example:

#!/bin/sh

echo "What is your favourite OS?"

Select Var in "Linux" "Gnu Hurd", "Free BSD", "other"; Todo

Break

Done

echo "You have selected $var"

The following is the result of the script running:

What is your favourite OS?

1) Linux

2) Gnu Hurd

3) Free BSD

4) Other

#? 1

You have selected Linux

4.loop

Loop expression:

While ...; Todo

....

Done

While-loop will run until the expression test is true. Would run while the expression so we test is true. The keyword "break" is used to jump out of the loop. The keyword "Continue" is used to skip to the next loop without performing the remaining parts.

The For-loop expression looks at a list of strings (strings separated by spaces) and assigns them to a variable:

for Var in ...; Todo

....

Done

In the following example, ABC is printed separately on the screen:

#!/bin/sh

For Var in A B C; Todo

Echo "Var is $var"

Done

Here is a more useful script showrpm that prints some of the RPM packet statistics:

#!/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 $*; Todo

If [-R "$rpmpackage"];then

echo "=============== $rpmpackage =============="

Rpm-qi-p $rpmpackage

Else

echo "Error:cannot Read file $rpmpackage"

Fi

Done

Here comes the second special variable $*, which contains all the input command-line parameter values. If you run showrpm openssh.rpm w3m.rpm webgrep.rpm This time $* contains 3 strings, that is, openssh.rpm, w3m.rpm and webgrep.rpm.

The For loop structure differs from the C language, and the basic structure of the For loop in BASH is:

For $var in [list]
Todo
#code Block
Done

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

#!/bin/bash

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

# If the list is enclosed in a pair of double quotes, it is considered an element
For day in "Sun Mon Tue Wed Thu Fri Sat"
Todo
Echo $day
Done

Exit 0

Note that in the above example, the variable day in the for row is not marked with the "$" symbol, whereas in the loop, the line variable $day the echo must be added with the "$" symbol. In addition, if you write for day without the following in [List] section, day will fetch all the parameters of the command line. such as this program:

#!/bin/bash

for Param
Todo
Echo $param
Done

Exit 0

The above program will list all command-line arguments. The loop body of the For loop structure is included in the Do/done pair, which is the characteristic of the subsequent while and until loops.

The basic structure of the while loop is:

while [condition]
Todo
#code Block
Done

This structure invites you to write an example to verify.

The basic structure of the until cycle is:

Until [condition is TRUE]
Todo
#code Block
Done

This structure also invites you to write an example to verify.

5. Quotes

The program expands wildcard characters and variables before passing any arguments to the program. What this means by extension is that the program replaces the wildcard character (such as *) with the appropriate filename and replaces the variable with the variable value. To prevent the program from making this substitution, you can use quotes: Let's look at an example, assuming there are some files in the current directory, two JPG files, mail.jpg and tux.jpg.

1.2 Compiling the shell script

#ch #!/bin/sh mod +x filename

echo *.jpg

Done

Use the./filename to execute your script. This will print out the results of the "Mail.jpg tux.jpg". quotation marks (single and double quotes) prevent this wildcard extension:

#!/bin/sh

echo "*.jpg"

Echo ' *.jpg '

This will print "*.jpg" two times.

Single quotes are more restrictive. It can prevent any variable from being extended. Double quotes can prevent wildcard extensions but allow variable extensions.

#!/bin/sh

Echo $SHELL

echo "$SHELL"

Echo ' $SHELL '

The results of the operation are:

/bin/bash

/bin/bash

$SHELL

Finally, there is a way to prevent this extension by using the escape character--the backslash:

Echo \ *.jpg

echo \ $SHELL This will output:

*.jpg

$SHELL

6. Here documents

When you want to pass a few lines of text to a command, here is a good way to find out if you have not seen a suitable translation for the word at this time. It is useful to write a helpful text for each script, and if we have the four here documents

You do not have to use the Echo function to output line by row. A "Here document" with shift by 2

-Shift;break;; # End of options

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

*) break;;

Esac

Done

echo "Opt_f is $opt _f"

echo "opt_l is $opt _l"

echo "The ' is $"

echo "2nd Arg is $"

You can run the script this way:

Cmdparser-l hello-f---somefile1 somefile2

The result returned is:

Opt_f is 1

opt_l is Hello

Is-somefile1 of the A-arg

2nd Arg is Somefile2

How does this script work? The script first loops through all the input command-line arguments, and the parameters are entered

Compares with a case expression, sets a variable if it matches, and removes the parameter. According to the practice of UNIX systems, the first input should be an argument containing a minus sign.

Part 2nd-Example

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

CP framework.sh MyScript

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

Binary to decimal conversion, the script b2d converts a binary number (for example, 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

would return 58

Help

Exit 0

}

Error ()

{

# Print an error and exit

echo "$"

Exit 1

}

Lastchar ()

{

# return ' last character ' a string in $rval

If [-Z "$"]; Then

# empty string

Rval= ""

Return

Fi

# WC puts some space behind the ' output ' is why we need sed:

Numofchar= ' Echo-n ' "$" | wc-c | Sed ' s///g '

# now cut out of the last Char

Rval= ' Echo-n ' "$" | Cut-b $numofchar '

}

Chop ()

{

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

If [-Z "$"]; Then

# empty string

Rval= ""

Return

Fi

# WC puts some space behind the ' output ' is why we need sed:

Numofchar= ' Echo-n ' "$" | 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 char:

Rval= ' Echo-n ' "$" | Cut-b 0-${numofcharminus1} '

}

While [-N ' $]; Todo

Case is in

-h) Help;shift 1;; # function Help is called

-Shift;break;; # End of options

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

*) break;;

Esac

Done

# The main program

Sum=0

Weight=1

# One ARG must be given:

[-Z ' $] && Help

Binnum= "$"

Binnumorig= "$"

While [-N "$binnum"]; Todo

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 the algorithm to use decimal and binary number weights (1,2,4,8,16,..), such as binary "10" can be converted to decimal: 0 * 1 + 1 * 2 = 2 We use the Lastchar function to get a single binary number. The function calculates the number of characters using WC–C and then uses the Cut command to remove the end of a character. The function of the chop function is to remove the last character.

File Loop procedure

Maybe you are one of the people who want to save all the messages sent to a file, but in a few months

Later, the file can become so large that it slows down access to the file. The following script Rotatefile

can solve this problem. This script can rename the Mail save file (assumed to be outmail) as OUTMAIL.1,

And for the OUTMAIL.1 became OUTMAIL.2 and so on 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 is 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 "$"

Exit 1

}

While [-N ' $]; Todo

Case is in

-h) Help;shift 1;;

-) break;;

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

*) break;;

Esac

Done

# input Check:

If [-Z "$"]; Then

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

Fi

Filen= "$"

# Rename any. 1,. 2 etc File:

For N in 9 8 7 6 5 4 3 2 1; Todo

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 testing the user for a filename, we have a 9 to 1 loop. File 9 is named 10, file 8 is renamed 9, and so on. After the loop completes, 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, of course, is to use the echo command. You can use Echo to print any variable values in any suspect error area. This is why most shell programmers spend 80% of their time debugging programs. The advantage of a shell program is that you don't need to recompile, and it doesn't take much time to insert an echo command.

The shell also has a real debug mode. If there are errors in the script "Strangescript", you can debug this:

Sh-x Strangescript

This executes the script and displays the values of all the variables.

The shell also has a pattern that does not need to execute a script just to check the syntax. You can use this:

Sh-n Your_script

This will return all syntax errors.

About bash shortcut keys under the console

Ctrl+u Delete all characters before the cursor
Ctrl+d deletes one character before the cursor
Ctrl+k all characters after the cursor is deleted
Ctrl+h deletes a character after the cursor
Ctrl+t the order of two characters before the switch cursor
CTRL + a move the cursor to the front
Ctrl+e move the cursor to the last side
Ctrl+p Previous Command
CTRL + N Next command
Ctrl+s Lock Input
Ctrl+q unlock
CTRL+F move the cursor to the latter character
CTRL+B move the cursor to the previous character
Ctrl+x Mark a position
CTRL + C clears the current input

The most basic theoretical basis
Here is a redirection definition for three files: 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 represents standard output, and 2 represents ' standard error '
Standard output
This example will redirect the display results of LS to a file.
Ls-l>ls-l.txt
Standard error
This example will cause the grep command to output errors in a file while it is running
Grepda*2>grep-errors.txt
Pipeline
In this section we will explain a very simple feature that you will definitely use in the future, which is the pipe.
Why would anyone use a pipe?
A pipe can make it very convenient for you to move the results of one program to another program.
An example of SED
This example uses a very simple piping function:
Ls-l|sed-e "S/[aeio]/u/g"
After we execute the following command: First Ls–l will execute first and it will output the result information but if it is followed by a pipe character, then it redirects the result to the SED program, and SED uses the substitution function, so this example performs the end of the ls– L ALL the English words containing aeio in the result are replaced by the word U.
To achieve ls–l*.txt by another method
This approach may be different from ls–l*.txt, but it avoids the occurrence of a nosuchfileordirectory message.
Ls-l|grep ". txt"
When Ls–l executes, it prints the results of the program to the GREP program and matches the TXT message.
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.