Shell script learning-Basic Elements

Source: Internet
Author: User
Tags echo command
ArticleDirectory
    • 4.1 redirection and MPs queue
    • Tr command details
    • 4.2 Special files:/dev/null and/dev/tty
1 variable

The shell variable name startsOne letter or underlineSymbol, followedAny length of letters, numbers, or underscoresSymbol.

Shell variable nameCharacterUnlimited length.

Shell variables can be used to save string values. There is no limit on the number of characters that can be saved.

Variable value assignment method: first write the variable name, followed by the = character, and finally the new value, there is no space in the middle. To retrieve the value of a shell variable, you must add $ before the variable name. When the given value contains spaces, enclose them with quotation marks:

First = Isaac middle = Bashevis last = singer#A single row can be assigned multiple times.Fullname ="Isaac Bashevis SINGER"#Use quotation marks when the value contains spaces.Oldname =$ Fullname#Quotation marks are not required here

However, when you connect several variables, you need to use quotation marks:

 
Fullname ="$ First $ middle $ last"#Double quotation marks are required.
2. Simple echo output
$ EchoNow is the timeForAll good menNow is the timeForAll good men
3. Gorgeous printf output

Printf command imitates CProgramThe printf () program in the library. It almost copies all the functions of this function. If you have written programs using C, C ++, awk, Perl, Python, or TCL, you should be familiar with its basic concepts. Of course, there will be some differences in Shell-level versions.

Like the echo command, the printf command can output a simple string:

 
Printf"Hello, world \ n"

Unlike echo, printf automatically provides a line feed symbol. You must specify the line feed as \ n. The complete syntax of the printf command is divided into two parts:

 
PrintfFormat-string[Arguments...]

The first part (Format-stringIs a string used to describe the arrangement of the output. It is best to enclose the string with quotation marks. This string contains literal characters and format declarations, which are special placeholders used to describe how to display corresponding parameters. The format declaration is divided into two parts: the percent sign (%) and the indicator. The most common format indicator is two, % s is used for strings, and % d is used for decimal integers.

Part 2 (Arguments...) Is the list of parameters corresponding to the format declaration.

In a format string, the characters are displayed literally, and the escape sequence is interpreted and then output to the corresponding characters. The format starts with "%" and ends with a character in the defined letter set. It is used to control the output of corresponding parameters. For example, output of the % s user string:

 
$ Printf"The first program always prints '% s, % s! '\ N"Hello worldthe first program always prints 'Hello world! '

 

4. Basic I/O redirection 4.1 redirection and Pipelines

Shell provides several syntax tags that can be used to change the source and destination of the default I/O.

*Input as <change standard

Program<FileYou canProgramToFile:

 
Tr-d' \ R' <DoS-File. Txt

*Output with> changed Standard

Program>FileYou canProgramToFile:

 
Tr-d' \ R' <DoS-File. Txt> Unix-File. Txt

This command first removes the ASCII carriage return in the dos-file.txt with TR and then outputs the converted data to the UNIX-file.txt. (The raw data in dos-file.txt does not change ).

> If the target file does not exist, a new one is created. However, if the target file already exists, it will be overwritten; the original data will be lost.

*To> attach to a file

Program>FileYou canProgramThe standard output is appended to the end of the file.

Like>, if the target file does not exist,> A new redirection is created. However, if the target file exists, it will not overwrite the file directly, but will append the data generated by the program to the end of the file:

 
ForFInDoS-File*. TxtDoTr-D' \ R' <$ F> Big-Unix-File. Txtdone

*To | create an MPS queue

 Program1|Program2You canProgram1ToProgram2.

 
Tr-d' \ R' <DoS-File. Txt | sort> Unix-File. Txt

 

Tr command details

Syntax

Tr [Options] Source-Char-list replace-Char-list

Purpose

Conversion character. For example, convert uppercase letters to lowercase letters. You can specify the characters you want to delete, and combine a string of repeated characters into one.

Common options

-C

Returns the source-Char-list. The character to be converted by tr, which is not listed in source-Char-list. This option is usually used with-D or-s.

-C

It is similar to-C, but it processes characters (which may contain multiple bytes of width) rather than binary bytes.

-D

Delete the characters listed in source-Char-list from the standard input instead of converting them.

-S

Duplicate characters. If the characters listed in source-Char-list appear repeatedly in the standard input, the character is condensed into one.

Behavior mode

Like a filter: read characters from standard input and write the results to standard output. Any input character that appears in source-Char-list is replaced with the corresponding character in replace-Char-list. POSIX-style characters and equivalent character sets are also applicable, and TR also supports the marking of repeated characters in replace-Char-list.

Warning

According to the POSIX standard definition,-C processes binary bytes, while-C processes the characters defined by the current locale.

4.2 Special files:/dev/null and/dev/tty

UNIX provides two special files that are particularly useful for shell programming. The first file/dev/null is a well-known bit bucket ). It is said that the data in this file will be lost by the system. That is to say, when the program writes data to this file, it will think that it has successfully completed the Data Writing operation, but actually did nothing. If you need to exit the command, rather than its output, the sub-function will be very useful. For example, to test whether a file contains a certain mode:

 
IfGrep Patten myfile>/dev/Nullthen...#When the mode is foundElse...#When the mode is not foundFi

In contrast, when read/dev/null, the end symbol of the file is returned immediately. Read/dev/null operations rarely appear in Shell programs, but it is very important to understand the behavior mode of this file.

Another special file is/dev/tty. When the program opens this file, UNIX will automatically redirect it to a terminal [an entity's console or serial port, it may also be a Pseudo Terminal that logs on through the network and a window. This is particularly useful when the program must read manual input (such as a password. In addition, it is convenient to use it to generate error information, but few people do this:

Printf " Enter new password:  "     #  Prompt Input Stty-echo #  Disable Automatic printing of input characters Read pass </dev/tty #  Read Password Printf "  Enter again:  "            #  Prompt again Read pass2 </dev/tty # Read again to confirm Stty echo #  Don't forget to enable the function of automatically printing input characters  #  ... 

The stty command is used to control various terminal settings. -The echo option is used to disable the function of automatically printing each input character. stty ECHO is used to restore this function.

 

Reference: <shell script Learning Guide>

 

 

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.