(Linux shell) Chapter One--Small trial sledgehammer (i.)

Source: Internet
Author: User
Tags arithmetic echo command

Source: (Linux Shell) Chapter One--Small trial sledgehammer (i.)


Starting today, let's study the book "Linux Shell Scripting Raiders".

1.1 Introduction

A shell script is usually a text file that starts with #!, as follows:

#!/bin/bash

There are two ways to execute shell scripts, such as the following:

SH script.sh or./script.sh

But before we execute the script, we need to execute permissions on the script, or the script won't execute.

chmod a+x script.sh

In the command line, if you need to execute multiple commands simultaneously, you can use the

Cmd1;cmd2


1.2 Interrupt Printing

1.2.1 Practical Walkthrough

Echo is the basic command for interrupting printing.

By default, Echo adds a line break after each call.

Just use double-quoted text, combined with the echo command to print the text on the break, similar to the text that does not need double quotation marks can also get the output of nursery rhymes:

The same task can also be done using single quotes:

These methods look like acacia, but each has some special uses and side effects, take a look at the following line of commands:

See the command line throwing an error that cannot be prefixed with an exclamation point. Therefore, if you want to print an exclamation mark, do not enclose it in double quotes, or you can precede it with a special transfer character slash to transfer the exclamation point:

When using echo with single quotes, bash does not evaluate variables (such as $var) in single quotes, but only as shown

Another command that can be printed is the same parameters used by printf,printf as the printf function in C. Such as:

See, the output printed by printf is not wrapped with a newline.

1.2.2 Supplemental Content :

Prints color output. Each color has a corresponding color code, such as: reset = 0, black = 30, red = 31, green = 32, yellow = 33, blue = 34, magenta =35, cyan = 36, white =37. To print color text, you can enter the following command:

1.3 Playing variables and environment variables

1.3.1 Practical Walkthrough

A variable can be assigned in the following ways:

Var=value

var is the variable name, and value is the one assigned to the variable, and if value does not contain any white space characters, it does not need to use quotation marks for reference, and it must use either single or double quotation marks. Note that var = value differs from Var=value. Rewriting var=value to var = value uses common errors, but the former is an assignment operation, while the latter is an equality operation. You can print out the contents of a variable by adding a $ prefix to the variable name

Var= "Value"

echo $var or Echo ${var}, you can see that the first command is wrong, and the 23rd command integer prints out the contents of the variable:

We can also refer to the variable values in the double quotation marks of the printf or echo command:


The Export command is used to set environment variables. Thereafter, any program executed from the current shell script inherits this variable. We can export specific variables in executing applications or shell scripts as needed. By default, there are a number of standard environment variables that are available for use by the shell. Path is one of them .

$ echo $PATH

Usually the value of $path is defined in/etc/environment or/etc/profile or ~/.BASHRC. If you need to add a new path in path, you can use:

Export path= $PATH:/home/user/bin

1.3.2 Supplemental Content:

To get the length of a string, you can use the following method or :

identify the current shell version :

echo $SHELL or Echo

Modify bash hint string

When we open a terminal or run a shell, we will see a prompt string similar to [email protected]:/home/$. The hints and colors in the different Gnu/linux release versions are also slightly different. We can use the PS1 environment variable to customize the hint text. The default shell hint text is set on a line in the file ~/.BASHRC. You can use the following command to list the line that sets PS1:

If you want to set the prompt string, you can enter:

Ps1= ">", as shown, the prompt has become ">" angle brackets, but such modifications only work on the current terminal, if a new terminal or restart the computer, it will revert to the previous prompt to modify. You must modify the value in the ~/.BASHRC if you want to set it to take effect.

1.4 Mathematical operations through the shell

1.4.1 Preparation Knowledge

In the bash shell environment, you can use Let, (()), and [] to perform basic arithmetic operations. The two tools, expr and BC, are also useful for advanced operations.

1.4.2 Practical Walkthrough

A value can be defined using a normal variable assignment method, which is then stored as a string. However, there are ways to make it work like a number, as shown in the following:

Of course, you can also do the self-increment or decrement of variables:

Other arithmetic operation methods:

BC is an advanced tool for mathematical operations, and this precision calculator contains a number of options. We can use it to perform floating-point arithmetic and apply some advanced functions:

Additional actions for setting the BC parameter:

1.5 Play-to-file descriptors and redirects

? 1.5.1 Preparation Knowledge

? We frequently use standard input (stdin), standard output (stdout), and standard error (STDERR) when scripting. Redirecting output to a file through content filtering is one of the fundamental tasks we do. When the command outputs text, the output text may be an error message, or it may be a normal (non-error) output message. By looking at the output text itself, we cannot distinguish between what is normal output text and which is the error text. However, we can solve this problem by file descriptor, which extracts the text that is associated with a particular descriptor.

The file descriptor is an integer associated with an open file or data stream. File descriptors 0,1 and 2 are reserved by the system.

? ? 0-----------stdin (standard input)

? ? 1-----------stdout (standard output)

? ? 2-----------stderr (standard error)

? 1.5.2 Practical Walkthrough

? ? Use the following method to redirect or save the output text to a file:

? echo "This is a sample text 1" > Temp.txt

? ? This method stores the output text in the file temp.txt by intercepting the file, meaning that the contents of the temp.txt are first emptied before the output of the Echo command is written to the file.

? ? Next look at another example:

? echo "This is a sample text 2" >> temp.txt

? ? This method appends the text to the destination file.

? ?> and >> are not the same. Although both operators can redirect text to a file, the former empties the file and then writes the content, which appends the content to the end of the existing file.

?     ?

? Look at what the standard error is and how to redirect it. When the command outputs an error message, the stderr information is printed. Take a look at the following example:

? ?

Here, + is an illegal parameter, so an error message will be returned. Note: When a command error is returned, it returns a non-0 exit status, and when the command completes successfully, it returns the number 0, which can be obtained from the special variable $? (run echo $ immediately after the command executes)

? ? Next, we do not let the error message print in the terminal, but instead into a file:

    ? ? Note that the command is LS + 2>out.txt. Error message output to OUT.txt

? ? We can also execute the standard output along with the standard error message in the same command:

? ? You can see that the error message and the standard output are exported to different files. You can also convert stderr to stdout with the following command, so that both stderr and STDOUT are redirected to the same file:

? ? cmd 2>&1 output.txt or cmd &> output.txt. Sometimes, some unnecessary information may be included in the output. If you don't want the terminal to be flooded with stderr, you can redirect the output of stderr to/dev/null, making sure everything is clean. Let's say we have three files, each of which is a1,a2,a3. However, the normal user does not have read-write-execute permission on the file A1. If you need to print the contents of all the files with the file name starting with a, you can use the Cat command:

? You can see that the A1 file does not have any permissions, but because I am logged in with the root user, it is still possible to read the content, if other users read the A1, will be error, then we can use the standard error output to capture errors output, and then output the contents of other files:

? ?

?   1.5.3 supplemental content?      ? ?

? ? commands that read input from stdin can accept data in a variety of ways. In addition, we can use cat and pipe to develop our own file descriptors, for example:

? ? cat File | Cmd

? ? cmd1 | Cmd2

? ? redirect files to command:

? ? cmd < file


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.