Getting started with Shell in Linux

Source: Internet
Author: User

This article introduces the shell commands in linux from five aspects, including Shell variables, basic structure of Shell, return value of Shell functions, detailed description of Shell functions, and special variables in Shell, which may be helpful for beginners.

Shell getting started Tutorial: Shell Variables

Variable

A variable is used to store data temporarily. It is a memory space. Bash shell and other programming languages do not have the "data form". That is to say, it does not distinguish whether a variable is an integer or float type by default, unless you declare the variable type using the declare statement. In bash shell, there is only one data type by default, which is a string consisting of characters. At the same time, the set variables only exist in the current shell, that is, each shell will maintain a copy of their own variables and will not affect each other. You can export variables to environment variables so that other shells can be referenced by the shell.

Naming rules for variables:

1. it can contain letters, numbers, and underscores.

2. The first character cannot be a number.

3. Case Sensitive

Variable settings:

Variable name = Value

Example: name = john

We recommend that you set the variable: name = "john" or name = 'john'

When referencing a variable, double quotation marks and single quotation marks are different. single quotation marks do not replace variables. In double quotation marks, if you want to suppress variable replacement, you must use the Escape Character backslash.

Reference variable:

$ Variable name

We recommend that you reference the variable: $ {variable name}

Environment variable:

Use any of the following methods to change the name to an environment variable.

Name = "john"
Export name
Export name = "john"
Declare-x name = "john"
Some important built-in variables of bash:

$1 ~ $ N? Parameter location. When n exceeds 9, use $ {n}, for example, $ {10}
$ * Represents all parameter locations and is considered as a string
$ @ Represents all parameter locations, but represents the serial number composed of parameter locations
$ # Number of parameters
$? Return Value of the previous command
$! ID of the previous background process
$ Current shell process ID
 

Basic Structure of Shell

Basic Structure of shell program

The shell structure is generally composed of set variables, built-in commands, shell Syntax structures, and functions.

Example: test. sh

The Code is as follows: Copy code

#! /Bin/bash
# Use/bin/bash as the interpreter of this script
# Define a function
Function my_fun (){
Echo "Hello, $1, today is $2"
}
# Defining the connected Variables
Name = $1
Today = 'date'
# Function call
My_fun "$ name" "$ today"


To run the above script, you must first grant the execution permission.

Chmod + x test. sh
Then execute

./Test. sh john
Output

Hello, john, today is Tue Jun? 14:51:46 CST 2010
Parent shell and child shell

Before executing a script, the environment is the parent shell. When executing the script, the parent shell depends on #! /Bin/bash, fork comes up with a new shell environment, and then runs it in the sub-shell. After the execution is complete, the sub-shell ends, and any of them returns to the parent shell, this will not affect the parent shell environment.
 

This figure shows the login shell process. When it is a non-login shell, only the marked part in the box is executed. We can see from this figure that the process is executed in the following situations.

Login (login)

/Etc/profile
~ /. Bash_profile
Log out)

~ /. Bash_logout
Execute the new shell in two cases:

1. Execute an Interactive shell

~ /. Bashrc
/Etc/bashrc
2. Execute a non-interactive shell. For example, execute the script to check the content of the BASH_ENV variable. If there is a definition, execute it.


Shell function return value

Shell functions generally return values in three ways:

1. return Statement (default return value)

The return Value of the shell function can be the same as that of other languages. It is returned through the return statement.

For example:

The Code is as follows: Copy code

#! /Bin/bash
Function mytest (){
 
Echo "mytest function"
Echo "argv [1] = $1"

If [$1 = "1"]; then
Return 1
Else
Return 0
Fi

}

Echo "mytest 1"
Mytest 1
Echo $?

Echo "mytest 0"
Mytest 0
Echo $?


If mytest 1; then
Echo "mytest 1"
Fi


If mytest 0; then
Echo "mytest 0"
Fi


Echo "end"


Define a function, mytest, which returns 1 based on whether the input parameter is 1; otherwise, return 0.

Obtain the return value of a function by calling the function or the value of the last execution.

In addition, the return value of the function can be directly used as the if judgment.

Note: return can only be used to return an integer. The difference between return and c is that return is correct, and other values are incorrect.

2. Global variables or environment variables

This is similar to the global variable in c.

The Code is as follows: Copy code

#! /Bin/bash

G_var =

Function mytest2 (){
Echo "mytest2"
Echo "args $1"
G_var = $1
Return 0
}

Mytest2 1

Echo "g_var = $ g_var"

Function mytest2 returns the result by modifying the value of the global variable.

3. When the above two methods fail

The two methods described above are generally useful, but there are exceptions.

For example:

The Code is as follows: Copy code


#! /Bin/bash

Function mytest3 (){
Grep "123" test.txt | awk-F: '{print $2}' | while read line; do
Echo "$ line"
If [$ line = "yxb"]; then
Return 0
Fi
Done
Echo "mytest3 here"
Return 1
}


G_var =

Function mytest4 (){
Grep "123" test.txt | awk-F: '{print $2}' | while read line; do
Echo "$ line"
If [$ line = "yxb"]; then
G_var = 0
Echo "g_var = 0"
Return 0
Fi
Done
Echo "mytest4 here"
Return 1
}

Mytest3
Echo $?

Mytest4
Echo "g_var = $ g_var"


The content in test.txt is as follows:

The Code is as follows: Copy code

456: kkk
123: yxb
123: test

The output is as follows:

Yxb @ yxb-laptop :~ /Document/personal document/shell function return value $./no_function.sh
Yxb
Mytest3 here
1
Yxb
G_var = 0
Mytest4 here
G_var =

We can see that mytest3 does not directly return after return, but executes the statement after the loop body. It also shows that mytest4 is the same. At the same time, in mytest4, modification to global variables does not help, and the value of global variables does not change at all.

Why is that?

The author believes that the reason why the return statement does not return directly is that the return statement is executed in the pipeline. The pipeline is actually another sub-process, and the return statement is only returned from the sub-process, however, when the while statement ends, the statement after the function body continues to be executed.

Similarly, the global variable is modified in the child process, but the modification of the child process cannot be reflected in the parent process. The global variable is only passed into the child process as an environment variable, the child process does not affect the parent process by modifying its environment variables.

Therefore, when writing shell functions, you must be clear when using pipelines. At this moment, it is returned from somewhere.

4. echo return value (explicit output)

In shell, the return value of a function has a very safe return method, that is, it is returned by outputting to the standard output. Because the child process inherits the standard output of the parent process, the output of the child process is directly reflected to the parent process. Therefore, the returned value is invalid due to the pipeline.

You only need to obtain the return value of the function.

The Code is as follows: Copy code

#! /Bin/bash

Function mytest5 (){
Grep "123" test.txt | awk-F: '{print $2}' | while read line; do
If [$ line = "yxb"]; then
Echo "0"
Return 0
Fi
Done
Return 1
}

Result = $ (mytest5)

If [-z $ result]; then
Echo "no yxb. result is empyt"
Else
Echo "have yxb, result is $ result"
Fi

The output is as follows:

View sourceprint?
1 have yxb, result is 0
This method is easy to use, but there are 1.1 things that must be paid attention to, and some things that are not the result cannot be output to the standard, such as debugging information, which can be redirected to a file to solve the problem, note that when using commands such as grep, remember 1>/dev/null 2> & 1 to avoid the output of these commands.

Echo output: Use the return value of a function as a parameter of another function.

The Code is as follows: Copy code


#! /Bin/bash
Dir =/cygdrive/d/server/ebin
Function display (){
Files = 'ls $ dir'
Echo $ files
}
Echo 'display'
 
Function filetype (){
Echo 'file $ Dir/$ 1' # type of the file to be detected
}
 
For file in 'display' # Call the display function to traverse the returned values.
Do
Filetype $ file # Check the file type and output it
Done

Summary:

$? To obtain the return value of the function. use $ (function name) to obtain the echo value of the function.


Shell functions

 

Shell functions are similar to Shell scripts, which store a series of commands. However, Shell functions exist in the memory rather than hard disk files, so the speed is very fast. In addition, Shell can also pre-process functions, therefore, function startup is faster than script startup.

1. Function Definition

Function Name (){
Statement
[Return]
}


The keyword "function" indicates defining a function, which can be omitted. It is followed by the function name. Sometimes the function name can be followed by a bracket. the symbol "{" indicates the function execution command entry, the symbol can also be in the row of the function name. "}" indicates the end of the function body. The two braces are the function bodies.

The statement can be any Shell command or other functions.

If you use the exit command in a function, you can exit the entire script. Generally, after the function is completed, the part that calls the function is returned for further execution.

You can use the break statement to interrupt function execution.

Declare-f can display the list of defined functions

Declare-F can display only the defined function names

Unset-f can delete functions from Shell memory

Export-f outputs the function to Shell

In addition, the function definition can be stored in the. bash_profile file, the function script, the command line, and the internal unset command to delete the function. Once the user logs out, Shell will not keep these functions.

2. function call

Function call instance:

The Code is as follows: Copy code

#! /Bin/bash
Function show (){
Echo "hello, you are calling the function"
}
Echo "first time call the function"
Show
Echo "second time call the function"
Show

3. Pass function parameters

The function can pass parameters through location variables. For example

Function name parameter 1 parameter 2 parameter 3 parameter 4

When the function is executed, $1 corresponds to parameter 1, and so on.

Instance:

The Code is as follows: Copy code

#! /Bin/bash
Function show (){
Echo "hello, you are calling the function $1"
}
Echo "first time call the function"
Show first
Echo "second time call the function"
Show second

4. function return value

The keyword "return" in a function can be placed anywhere in the function body. It is usually used to return some values. After the Shell executes return, it stops executing and returns to the calling line of the main program, the return value can only be 0 ~ An integer between 256. the return value is saved to the variable "$ ?" .

Instance:

The Code is as follows: Copy code
#! /Bin/bash
Function abc (){
RESULT = 'expr $ 1% 2' # returns the remainder.
If [$ RESULT-ne 0]; then
Return 0
Else
Return 1
Fi
}
Echo "Please enter a number who can devide by 2"
Read N
Abc $ N
Case $? In
0)
Echo "yes, it is"
;;
1)
Echo "no, it isn' t"
;;
Esac

Note that the parameter is passed here. The number read above must be added with the $ symbol to be passed to the function. I didn't know where the error was at the beginning, it took only half a day to find out that an error occurred.

5. function loading

How can we call a function in another file?

Here is a method. For example, if the show function is written in function. sh, we can use

The Code is as follows: Copy code


Source function. sh

2 show

In this way, you can call it.

6. delete a function

Usage: unset-f function name

7. function variable scope

By default, a variable has a global scope. If you want to set it as a local scope, you can add the local

For example:

The Code is as follows: Copy code


Local a = "hello"

Using local variables, the function automatically releases the memory space occupied by the variables after execution, thus reducing the consumption of system resources. When running large programs, defining and using local variables is particularly important.

8. Function nesting

Functions can be nested. For example:

The Code is as follows: Copy code

#! /Bin/bash
Function first (){
Function second (){
Function third (){
Echo "------ this is third"
}
Echo "this is the second"
Third
}
Echo "this is the first"
Second
}

Echo "start ..."
First

 
Special variables in Shell

I. Reserved Variables

The $ IFS Variable contains the delimiter used to separate input parameters. The default Delimiter is space.

The $ HOME variable stores the root directory path of the current user.

The $ PATH variable stores the default PATH string of the current Shell.

$ PS1 indicates the first system prompt.

$ PS2 indicates two system prompts.

$ PWD indicates the current working path.

$ EDITOR indicates the Default EDITOR name of the system.

$ BASH indicates the path string of the current Shell.

$0, $1, $2 ,...

This parameter indicates the first, second, and other parameters that the system sends to the script program or the script program to the function.

$ # Indicates the number of command parameters of the script program or the number of function parameters.

$ Indicates the process Number of the script program. It is often used to generate a temporary file with a unique file name.

$? Indicates the return status value of the script program or function. The normal value is 0. Otherwise, it is a non-zero error number.

$ * Indicates all Script Parameters or function parameters.

$ @ Is similar to $ *, but safer than $.

$! Indicates the process Number of the last process running in the background.

Ii. Random Number

Random numbers are frequently used. BASH also provides this function. See the following program:

The Code is as follows: Copy code

#! /Bin/bash
# Prints different random integer from 1 to 65536
A = $ RANDOM
Echo $
Exit 0

This program can randomly print an integer between 1 and 65536 during each execution.

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.