The shell Getting Started tutorial in Linux

Source: Internet
Author: User
Tags function definition variable scope

Shell Getting Started Tutorial: Shell variables

Variable

A variable is a place to store data temporarily, and is a memory space. Bash shell and other programming languages, there is no "data form", which means that the default is not to distinguish between a variable is an integer or a floating-point type, unless you use the DECLARE statement to declare the variable type. In the bash shell, the default is only one type of data, the string consisting of characters. At the same time, the set of variables only exists in the current shell, that is, each shell will maintain a copy of their own variables, will not affect each other. You can export variables to environment variables so that other shells can be referenced by the shell.

Named rules for variables:

1. May use the English alphabet, the numeral and the underline composition

2. The first character cannot be a number

3. Case sensitive

Variable setting:

Variable name = value

For example: Name=john

It is recommended that you set the variable: name= "John" or Name= ' John '

There is a difference between using double quotes and single quotes when referencing a variable, and the single quotation mark does not replace the variable. In double quotes, if you want to suppress variable substitution, you need to use the escape character backslash

Reference variables:

$ variable Name

It is recommended to refer to variables such as: ${variable names}

Environment variables:

Use any of the following methods to make name into an environment variable

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

$ $n? The position of the parameter. When n exceeds 9, use ${n}, such as ${10}
$* represents all the parameter positions and is treated as a string
The $@ represents all the parameter positions, but represents the serial of the various positional parameters
Number of $# parameters
$? return value of previous command
$! Number of previous background process
$$ the current shell process number

The basic structure of the shell

The basic composition structure of shell program

The shell structure is mainly composed of set variables, built-in commands, shell syntax structure, functions.

Use instance Description: test.sh

The code is as follows Copy Code

#!/bin/bash
#说明使用/bin/bash as the interpreter for this script
#定义一个函数
function My_fun () {
echo "Hello, $1,today is $"
}
#定义连个变量
Name=$1
today= ' Date '
#函数调用
My_fun "$name" "$today"


The above script will need to do some action to run, first give execution permission

chmod +x test.sh
And then execute

./test.sh John
Output

Hello, John,today is Tue June? 1 14:51:46 CST 2010
Parent Shell and child shell

Before the script is executed, the environment is the parent shell. At the time of script execution, the parent shell #!/bin/bash,fork out a new shell environment, executes it in a child shell, finishes after execution, and returns to the parent shell, which does not affect the parent shell's environment.

This image is the login shell process, and when it is the non-login shell, only the part of the callout in the box is executed. From this diagram we can know that in the following several cases, the process of execution.

Login (Login)

/etc/profile
~/.bash_profile
Logout (Logout)

~/.bash_logout
Execute the new shell, split into two situations

1. Perform an interactive shell

~/.bashrc
/etc/bashrc
2. Performing a non-interactive shell, such as executing a script, checks the contents of the BASH_ENV variable and executes it if it is defined.


return value of the Shell function

The return value of a shell function typically has 3 ways:

1. Return statement (default returned value)

The return value of the Shell function can be returned through the return statement, just as it is for other languages.

Like what:

The code is as follows Copy Code

#!/bin/bash
function MyTest () {

echo "MyTest function"
echo "argv[1] = $"

if [$ = "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"


First defines a function, mytest, which will return 1 depending on whether the input parameter is one, or return 0.

Gets the return value of the function by calling the function, or by the last executed value.

Alternatively, you can use the return value of the function directly as an if judgment.

Note: Return can only be used to return an integer value, and the difference from C is that it is returned as correct and the other values are errors.

2, global variable or environment variable

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 $"
G_var=$1
return 0
}

Mytest2 1

echo "G_var= $g _var"

function Mytest2 Returns the result by modifying the value of a global variable.

3. When the above two methods fail

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

Like what:

The code is as follows Copy Code


#!/bin/bash

function Mytest3 () {
grep "123" Test.txt | Awk-f: ' {print $} ' | While read line;d o
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 $} ' | While read line;d o
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 contents of the Test.txt are 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=

You can see MYTEST3 in return after actually not directly returned, but the execution of the statement after the loop body, and see the same in Mytest4, at the same time, in Mytest4, the changes to the global variables do not help, the value of global variables have not changed.

What's the reason for that?

In my opinion, the return statement is not returned directly because the returns statement is executed in the pipeline, and the pipe is actually another subprocess, and return is only returned from the child process, except that the while statement ends and the statement after the function body continues to execute.

Similarly, a global variable is modified in a subprocess, but the modification of the child process is not reflected in the parent process, and the global variable is passed into the subprocess as an environment variable, and the child process modifies its own environment variables without affecting the parent process.

So when you're writing a shell function, it's important to be clear when you use the pipe, and where you're returning from.

4, Echo return value (explicit output)

In fact, in the shell, the return value of the function has a very safe way of returning, that is, through output to standard output. Because the child process inherits the standard output from the parent process, the output of the child process is directly reflected to the parent process. Therefore, there is no condition mentioned above that caused the return value to be invalidated by the pipe.

You just need to get the return value of the function outside.

The code is as follows Copy Code

#!/bin/bash

function Mytest5 () {
grep "123" Test.txt | Awk-f: ' {print $} ' | While read line;d o
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 is a good way to do it, but it's important to note that you can't output something that is not a result to the standard, such as debugging information, which can be redirected to a file to resolve, especially when using a command such as grep, be sure to remember 1>/dev/null 2 >&1 to avoid the output of these commands.

echo Output Another tip: Use the return value of a function as an argument to 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 ' #输出待检测文件的类型
}

For file in ' Display ' #调用display函数, iterate over its return value
Todo
FileType $file #检测文件类型并输出
Done

Small summary:

With $? To get the return value of the function, using the $ (function name) to get the echo value of the function.


A detailed explanation of shell functions

Shell functions are similar to shell scripts, which hold a series of instructions, but the shell functions in memory, rather than hard disk files, so fast, in addition, the shell can also preprocess functions, so the function is started faster than the script.

1. Function definition

function functions name () {
Statement
[Return]
}


The keyword function representation defines a function, it can be omitted, then the function name, and sometimes the function name can be followed by a bracket, the symbol "{" represents the entry of the function Execution command, the symbol can also be in the function name that line, "}" to indicate the end of the function body, between the two braces is a function body.

The statement part can be any shell command, or it can call other functions.

If you use the Exit command in a function, you can exit the entire script, which, in general, returns to the part of the calling function after the function finishes.

You can use the break statement to interrupt the execution of a function.

Declare–f can display a list of defined functions

Declare–f can display only the defined function names

Unset–f can remove functions from shell memory

Export–f output the function to the shell

In addition, the definition of a function can be placed in a. bash_profile file or in a script that uses a function, can also be placed directly on the command line, and can be removed using the internal unset command. Once the user logs off, the shell will no longer hold these functions.

2, the function of the call

Instance of a function call:

The code is as follows Copy Code

#!/bin/bash
Function Show () {
echo "Hello, you are calling the function"
}
echo "Call the function"
Show
echo "Second time called" function "
Show

3. Transfer of function parameters

Functions can pass arguments by positional variables. For example

Function Name parameter 1 parameter 2 parameter 3 parameter 4

When the function executes, the corresponding argument 1, and so on.

Instance:

The code is as follows Copy Code

#!/bin/bash
Function Show () {
echo "Hello, you are calling the function $"
}
echo "Call the function"
Show a
echo "Second time called" function "
Show second

4, the return value of the function

The keyword "return" in a function can be placed anywhere in the function body, typically used to return some value, the shell stops executing after it executes to return, returns to the calling line of the main program, return value can only be an integer between 0~256, return value will be saved to the variable "$?" In

Instance:

The code is as follows Copy Code
#!/bin/bash
Function abc () {
result= ' expr $2 ' #表示取余数
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

Here to pay attention to the parameters passed, read in the above number, must add $ symbol to pass to the function, I just don't know where is wrong, looking for a long time to know that it is here to make a mistake.

5, the function of loading

If the function is in another file, how do we call it?

There's a way here. For example, the show function is written in the function.sh, and we can use

The code is as follows Copy Code


SOURCE function.sh

2 Show

So that we can call the.

6, the deletion of the function

Usage: unset–f function name

7, the function of the variable scope

By default, a variable has a global scope, and if you want to set it as a local scope, you can add it before it

For example:

The code is as follows Copy Code


Local a= "Hello"

The use of local variables, so that after the completion of the function, automatically free the memory space occupied by variables, thereby reducing the consumption of system resources, in the running of large programs, the definition and use of local variables is particularly important.

8, the function of nesting

Functions can be nested, instance:

The code is as follows Copy Code

#!/bin/bash
function A () {
function second () {
function third () {
echo "------This is third"
}
echo "This is the second"
Third
}
echo "This is the"
Second
}

echo "Start ..."
The


Special variables in the shell

One, retention variables

$IFS this variable, the split character used to segment input parameters is saved, and the spaces are implicitly known.

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

The default path string for the current Shell is stored $PATH this variable.

$PS 1 represents the first system prompt.

The two system prompts that are represented by the $PS 2.

$PWD represents the current work path.

The $EDITOR represents the default editor name for the system.

$BASH represents the path string for the current Shell.

$, $, $, ...

Represents the No. 0, first, and second parameters that the system passes to a script or script program to a function.

$# represents the number of command arguments or the number of parameters of a function for a script program.

$$ represents the process number of the script, often used to generate a unique temporary file for the file name.

$? Represents the return state value of a script program or function, normally 0, otherwise a non-zero error number.

$* represents all the script parameters or function parameters.

$@ and $* have similar connotations, but are more secure than $*.

$! Represents the process number of the most recent process running in the background.

Second, random number

Random numbers are often used, and this feature is provided in BASH, see the following program:

The code is as follows Copy Code

#!/bin/bash
# prints different random integer from 1 to 65536
A= $RANDOM
Echo $a
Exit 0

This program can randomly print out an integer size between 1 and 65536 at a time of 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.