Linux Learning Chat (i)--shell basic operations and commands

Source: Internet
Author: User
Tags arithmetic function definition

Linux Learning Chat (i)

--Shell Basic operations and commands

(Reproduced please attach this article link--linhxx)

1, #!/bin/sh

Placed at the beginning of the program, expressed in/bin/sh way to parse.

2. Variables

1) variable assignment varname= ' xxx ', in addition to variable assignment and in the For Loop statement header, in other cases the variables used in bash must have a "$" symbol in front of the variable, that is, using the $varname variable. The more standard way to refer to a variable is ${str}, $STR is just a simplification of ${str}. In complex situations where ambiguity is possible, it is best to use the notation with {}.

2) When assigning a value to a variable, the equals sign = no spaces on either side.

3) Local variables are defined, and export defines global variables.

4) Reserved Variables:

$IFS This variable holds the split character used to split the input parameter, which is the default space.

$HOME This variable stores the current user's root directory path.

$PATH This variable stores the default path string for the current Shell.

$PS 1 indicates the first system prompt.

The two system prompt represented by $PS 2.

$PWD represents the current working path.

$EDITOR represents the default editor name for the system.

$BASH represents the path string for the current Shell.

$RANDOM randomly generates an integer that is between 1 and 65536 in size.

5) Special operation of variables:

${var-default} indicates that if the variable $var has not been set, the $var is not set and returns the default value that follows.

${var=default} indicates that if the variable $var has not been set, then the default value of the following is taken.

${var+otherwise} indicates that if the variable $var has been set, the value of otherwise is returned, otherwise empty (NULL) is returned.

${VAR?ERR_MSG} indicates that if the variable $var has been set, the value of the variable is returned, or the subsequent err_msg is output to the standard error output.

${var#pattern},${var# #pattern} is used to peel the shortest (longest) and the leftmost string matching the pattern from the variable $var.

${var%pattern},${var%%pattern} is used to strip the shortest (longest) and the rightmost string matching the pattern from the variable $var.

${var:pos} indicates that the variable $var before the POS characters are removed.

${var:pos:len} represents the first Len character of the remaining string after the first POS character is removed from the variable $var.

${var/pattern/replacement} indicates that the first occurrence of the pattern pattern in the variable $var is replaced with a replacement string.

${var//pattern/replacement} indicates that all pattern patterns appearing in the variable $var are replaced with replacment strings.

3, && and | | and |

1) a && B means execute a first, and then execute B successfully.

2) a| | B means execute a, success does not execute B, otherwise B.

3) a|b indicates that a is executed first, and the result of execution is used in the process of executing B.

4. Special symbols

1) # for the beginning of the definition, the beginning of the other line indicates that the bank comment does not execute

2); Multiple statements are placed on the same line with this separation.

3);; When using case, as the end of each option.

Varname=b

Case ' $varbname ' in

[A-z]) echo "ABC";;

[0-9]) echo "123";;

Esac

4) Single and double quotation marks: Same as PHP

5) ' (anti-quote), outputs the result of the command execution to the variable.

The CP ' mkdir back ' test.sh is executed first in the anti-quote, then executes the copy CP command.

6):

1. A built-in command of the empty command bash, the exit code is 0. Works the same as true.

2. variable extension/string substitution: > File Empty This file is the same as the cat, Dev/null file. But with: No new process is generated, because it is built-in command.

7) parentheses ()

1. Command group, the parentheses inside the command as a child shell, the remainder of the script is not available, the variable has a scope problem. The result of the following output is 123, which is useless outside the parentheses within the parentheses.

A=123

(a=321;)

echo "a = $a"

2. Initialize array: arr= (1 3 5 7 9)

8) curly Braces {}

1. File name extension CP T.{txt,bak} Copy the contents of T.txt to T.bak

2. code block, in contrast to parentheses, you can still use the variables inside the curly braces. Output 321 below.

A=123

{a=321;}

echo "a = $a"

9) Brackets []

1. If the conditions are placed in brackets if [$a-gt 10], spaces are required on both sides of the square brackets.

2. Used to reference array elements, with PHP

<, > and <<, >>

First, two symbols and a symbol of the comparison, two symbols of the output is appended to the file, a symbol of the meaning of the direct output to the file (overwrite the original content).

Second, symbols represent redirects, greater than less than with-GT and-lt.

Example: Sort >>name.txt <

1. Sort >>name.txt The results of the sort command to mask output and redirect to the end of the Name.txt file (redirect standard output).

2. Name.txt<

Additional content:

Linux input and output three standard: standard input, standard output, standard error output, respectively, is 0/1/2, combined to use is sort > name.txt that is sort 1> name.txt, but to say the error output with sort 2> Name.txt, the content will be output to name.txt. If you want to output both the standard output and the standard error output, you need sort > name.txt 2>& 1, or use sort >& name.txt.

11).

Reads and executes the. sh file and executes under the current shell (./xxx.sh is executed under the child shell)

5, $

1) $$ The ID of the current shell process

2) The file name of the current script

3) $n arguments passed to the script or function. N is a number that represents the first few parameters. For example, the first parameter is $ $, and the second argument is $ A. Up to 9, tenth can not be obtained with $ $, need to store $ after, with the shift command to remove the first variable, then $9 is the tenth variable entered.

4) $# The number of arguments passed to the script or function.

5) $* all parameters passed to the script or function.

6) [email protected] All parameters passed to the script or function. When enclosed by double quotation marks (""), it is slightly different from $*. "$*" will all parameters as a whole, output all parameters in the form of "$ $ ... $n"; "[email protected]" will separate the parameters to "$" "$" ... All parameters are output in the form "$n".

7) $? The exit state of the last command, or the return value of the function.

6. Judgment

Execute man test to see the types that all test expressions can compare and judge.

-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

The-x file can be performed on the current user

-G file GID flag is set

The UID flag of the-u file is set

-O file belongs to the current user

-G file has the same group ID as the current user

file1-nt file2 file file1 than file2 update

File1-ot file2 file file1 older than file2

File1-ef file2 file file1 is a hard link to file2

If [-x/root] can be used to determine whether the/root directory can be entered by the current user

The corresponding action integer action 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 empty-Z

Not empty-N, recommended use! -Z instead

Last time I read it, I made a change to-n

Like what:

Compare integers A and b for equality write if [$a = $b]

Determine if integer A is greater than integer b to write if [$a-gt $b]

To compare strings A and b for equality write: if [$a = $b]

To determine if string A is empty write: if [-Z $a]

Determine if integer variable A is greater than B to write: If [$a-gt $b]

Note: There are spaces left and right around the "[" and "]" symbols.

7. Commissioning

Sh-n Your_script does not need to execute the script just to check the syntax of the pattern, returning all syntax errors.

Sh-x Strangescript executes the script and displays the values of all variables.

8, [[]] and [] Difference

1) Digital test:-eq-ne-lt-le-gt-ge,[[] [] consistent with []
2) file test:-R,-L,-W,-X,-F,-D,-S,-nt,-ot,[[] [] consistent with []
3) string Test: > < = (same = =)! =-n-z, do not use "<=" and ">=", [[]] same as [], but in [],> and < must be escaped with \, \> and \<
4) Logic test: [] for-a-o! [[]] for && | | !
5) Mathematical operation: [] cannot use [[]] can use +-*/%
6) Combination: Digital (operational) tests, file tests, character tests that can be connected by their logical symbols

Both use spaces to separate operators and values.

9, (())

Specifically for numeric operations, set the exit status to 1 if the expression evaluates to 0, or 0 if the evaluation is not a value of 0. There is no need to escape the operator between ((and)). Arithmetic is only for integers. In addition to 0, errors are generated, but no overflow occurs. You can perform arithmetic, logical, and bitwise operations that are common in the C language.

The following two methods all output 100:

((i=1+99)); Echo $i

i=99; ((i++)); Echo $i

There are no spaces for symbols and values under this method, and [[]] are not the same.

10. &

The & at the end of the command, which means executing the command in a non-blocking manner, without waiting for the result to execute, while executing the line command.

11. Functions

The definition of a function must precede the function's use.

The definition of a function parameter does not need to be made at the function definition, but only when the function is called with BASH's reserved variable ... To be quoted on it.

The return value of BASH can be specified with a return statement that returns a specific integer, and the return value is the result of the last statement of the function (typically 0 if execution fails and returns an error code) If no return statement is explicitly returned. BASH requires the return value to be an integer and cannot return a string variable with a return statement.

The return value of the function is passed through $ in the program body that called the function. Reserved words to get.

For example:

Square () {

Let "res = $ * $"

Return $res

}

Square $

Result=$?

12. Select

BASH provides a small statement format that allows the program to quickly design a menu of user interaction choices for a character interface that is implemented by the SELECT statement, with the syntax of the SELECT statement:

Xxx= ' a b C '

Select Var in $xxx

Do

statments Use $var

Done

After the syntax structure is executed, BASH adds all the items in the $xxx column to the screen waiting for the user to choose, and after the user makes a selection, the variable $var contains the selected string, and then the variable can be manipulated.

13. Read

Waits for the user's input and takes the result of the user input as a variable.

Read NAME

echo "hi! $NAME! "

--written by Linhxx

More recent articles, please pay attention to the public number "machine learning", or scan the right QR code.

Linux Learning Chat (i)--shell basic operations and commands

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.