Series article starter platform for Jelly want personal blog. Jelly think, is an original technical article sharing site. Here jelly will share his technical experience, technical gains and losses, technical life. I want to wait for you in jelly, and I hope you can share with me your technical loss and expectations.
The Magic of Linux
I'm not going to tell you how magical Linux is. As a code farmer in an IT world, more or less will come into contact with Linux, no matter how you touch Linux, some of these commands will certainly be more or less understood. Linux is not your must-have equipment, but equipped with Linux, for your career must be a profit and no harm. Based on this, I contacted Linux, and then I learned a shell script, in this article, as a shell script learning a note, for later browsing.
What the shell can do
Learning a knowledge is based on interest, which is a reason; another reason is to work. Well, I'm a noble one, and I'm not going to learn shell scripts for a living, purely for the sake of interest, to make up for the regret that I left behind when I didn't learn shell scripts in college. And more people learn that the shell is not like me, more to work, solve practical problems in the work and decided to look at the shell script, then the shell script in the work of what? First look at the following questions:
- Do you often need to deal with repetitive tasks?
- Do you often find that using high-level languages, such as C + +, to handle something to find overqualified?
- Do you often need to do some batch processing tasks in your work?
- ......
If for the above question, if you answer "YES". Then you need to learn more about Linux shell scripts. Well, presumably you've decided to go and see the shell. Come on.
A simple shell
Let's start with a simple shell script that has a simple understanding of the shell as a whole.
#!/bin/bashcd ~ # 切换到用户的主目录,也就是/home/xxxmkdir shell_test # 创建一个名为shell_test的文件夹for ((i=0; i<10; i++)) # Shell的for循环do touch test_$i.txt #创建空文件,文件名为test_0.txt, test_1.txt ...done
The above is a simple shell program that implements the function as:
- Create a Shell_test folder in the user's home directory;
- Create an empty file in the user's home directory with 10 specified named formats.
Because it is the first shell program, it is necessary to explain it one line at a glance, leaving a good impression.
- The first line: Specify the script interpreter, here is the interpreter with/bin/bash;
- Second line: Switch to the current user's home directory;
- Third line: Create an empty directory named Shell_test;
- Line fourth to fifth: For Loop, total loop 10 times;
- Line six: Create 10 empty files named Test_0.txt, test_1.txt format.
cd
, mkdir
and touch
are all system-brought programs, generally in the /bin
directory, and for
, do
and done
are the shell's keywords.
#
the lines in the shell that begin with are comments.
After a simple program, we begin to get into the shell grammar learning.
Variable
Start with the variable and learn the journey.
Basic knowledge
- In the shell, it is not necessary to declare the variables before using them, but to create them by using them;
- By default, all variables are treated as strings and stored as strings;
- Shell variables are case-sensitive;
- In the shell, by adding a symbol to the variable name before it
$
accesses its contents, you must precede it with a symbol whenever you want to get the contents of the variable $
;
The following is a detailed description of the above through a shell script:
#!/bin/bashvar1=10 #定义一个变量var1#定义一个变量var2,对于字符串中有空格的情况,需要使用引号将字符串括起来,#此外等号两边不能有空格var2="Jelly Think"echo $var1 #获取变量var1的值echo $var2 #获取变量var2的值
Using the Read
In the shell, we can use read
a command to assign a user's input to a variable. This command requires a parameter, which is the variable name to be read into the user's input data, and then waits for the user to enter the data. Typically, the read command ends when the user presses the ENTER key. For example, the following code:
#!/bin/bashread var1 #读入用户输入的var1变量的值echo $var1 #输出var1的值exit 0
Tips for using quotation marks
Also in the above code, if the string contains spaces, you need to enclose the string in quotation marks, which is just a simple use of quotation marks.
The behavior of variables such as $var1 in quotation marks depends on the type of quotation mark you are using. This sentence has the following two-storey meanings:
- If you put a $ variable expression in double quotation marks, the program executes to this line and replaces the variable with its value;
- If you put a $ variable expression in single quotation marks, there will be no substitution phenomenon;
However, we can remove its special meaning by adding a character before the $ character, which is \
often said to be an escape character. Here's a simple code to understand what the above means:
#!/bin/bashvar1="JellyThink"echo "This is $var1" #输出:This is JellyThinkecho 'This is $var1' #输出:This is $var1echo "This is \$var1" #输出:This is $var1exit 0
Environment variables
When a shell script starts executing, some variables are initialized according to the values in the environment settings, and generally the following are common:
- $HOME: The current user's home directory, for example:
/home/jelly
;
- $PATH: A colon-delimited list of directories used to search for commands;
- The name of the $0:shell script;
- $#: The number of arguments passed to the script;
- The process number of the $$:shell script, which is typically used by the script to generate a unique temporary file.
Parameter variables
If the script is called with parameters, some additional variables are created. Even if no arguments are passed, the environment variable $ #也依然存在, except that its value is 0. For example the following strength code:
#!/bin/bash#参数的命名是$1、$2......#$0表示脚本的名字#输出参数个数echo "参数个数为:$#"echo "脚本名字:$0"echo "第一个参数:$1"echo "第二个参数:$2"exit 0
The output is as follows:
参数个数为:2脚本名字:./argsDemo.sh第一个参数:Jelly第二个参数:Think
Conditional judgment
We know that all programming languages are based on the ability to test and judge conditions and to take different actions based on the results of the tests. Before summing up, look at the conditional structures that you can use in the shell script, and then look at the control structures that use these conditions.
A shell script can judge the exit code of any command that can be invoked from the command line, including the shell script we wrote. This is why it is important to include a command that returns a value at the end of all the scripts that you write exit
.
Test or [command
In practice, most scripting programs use the Shell's Boolean judgment commands extensively [
test
. On some systems, the two commands are actually the same, just for readability, and when using [
commands, we also use symbols ]
to end. Write so many programs, or the first time see, will one [
as a command. I'm ignorant the count. Here's a simple example to look at test
and [
how to use it.
#!/bin/bashif test -f testDemo.shthen echo "testDemo.sh exists."fiif [ -f test.c ]then echo "test.c exists."else echo "I cannot find exists."fiexit 0
We use it -f
to determine if the specified file exists. test
the condition types that the command can use can be categorized as 3 classes:
- string comparisons;
- Arithmetic comparison;
- FILE-related condition tests.
Let's look at the following separately.
string comparison |
Results |
string1 = string2 |
If two strings are the same, the result is true |
String1! = string2 |
If two strings are different, the result is true |
-N String |
If the string is not empty, the result is true |
-Z String |
If the string is an empty string (null), the result is true |
arithmetic comparison |
result |
expression1-eq expression2 |
If two expressions are equal, the result is true |
expression1-ne expression2 |
If two expressions are not equal, the result is true |
expression1-gt expression2 |
|
expression1-ge expression2 |
|
expression1-lt expression2 |
if Expre Ssion1 is less than expression2, then true |
expression1-le expression2 |
|
!expression |
The expression is false, the result is true, and vice-versa |
file Condition Test |
Results |
-D File |
True if the file is a directory |
-F File |
True if the file is a normal file, or it can be used to test whether the file exists |
-R File |
If the file is readable, the result is true |
-S file |
If the file size is not 0, the result is true |
-W File |
If the file is writable, the result is true |
-X File |
If the file is executable, the result is true |
Control structure
The shell also has a set of control structures that are similar to the control interfaces in other programming languages, and they are summarized separately below.
If statement
The structure is as follows:
if conditionthen statementselse statementsfi
code example:
#!/bin/bashvar1=Jelly #这个是赋值,不能有空格分隔var2=Thinkif [ $var1 = $var2 ] #‘=’号两边都需要空格分隔then echo "$var1 = $var2"else echo "$var1 != $var2"fiexit 0
elif statements
The structure is as follows
if conditionthen statementselif condition statementselse statementsfi
A problem that is prone to error. For example, the following code:
#!/bin/bashecho "Is it morning? please answer yes or no."read timeofdayif [ $timeofday = "yes" ]then echo "Good morning."elif [ $timeofday = "no" ]then echo "Good afternoon."else echo "Sorry, $timeofday not recognized. Enter yes or no." exit 1fiexit 0
The above code is very simple, run the following, if you do not enter yes
or no
, will run an error, get the following message:
./elifDemo1.sh: line 6: [: =: unary operator expected./elifDemo1.sh: line 9: [: =: unary operator expected
Why is this? In the code if [ $timeofday = "yes" ]
, when I do not enter anything, this if
statement becomes so if [ = "yes" ]
, obviously, this is not a valid condition. To avoid this, we must enclose the variable in quotation marks and change it to this if [ "$timeofday" = "yes" ]
. There's no problem with that.
For statement
The structure is as follows:
for variable in valuesdo statementsdone
code example:
#!/bin/bashfor foo in Jelly Think Websitedo echo $foodoneexit 0
In the beginning of the article, that simple code, also contains for
the simple use.
While statement
The structure is as follows:
while conditiondo statementsdone
code example:
#!/bin/bashecho "Enter password: "read pwdwhile [ "$pwd" != "root" ]do echo "Sorry, try again." read pwddoneexit 0
Until statements
The structure is as follows:
until conditiondo statementsdone
It while
is similar to the loop, except that the condition test is reversed, that is, the loop executes repeatedly until the condition is true.
Case statement
The structure is as follows:
case variable in pattern [ | pattern] ...) statements;; pattern [ | pattern] ...) statements;; ...esac
case
The code structure is relatively complex. case
structs have the ability to match multiple schemas and then execute multiple related statements, making it ideal for handling user input. Here's a look at case
the specific use of the example.
#!/bin/bashecho "Is it morning? Please answer yes or no."read inputcase "$input" in yes ) echo "Good Morning.";; no ) echo "Good Afternoon.";; y ) echo "Good Morning.";; n ) echo "Good Afternoon.";; * ) echo "Sorry, answer not recognized";;esacexit 0
When the case
statement is executed, it input
compares the contents of the variable to each string in turn. Once a string matches the input successfully, the case
command executes )
the code immediately following the closing parenthesis and ends.
In code, the representation of the last face *
matches any string, and when we write the code, we always add one after the other *
to ensure that if no strings are matched, the case
statement executes a default action.
Because of the case
complexity, we have to have another piece of code, the use of the following:
#!/bin/bashecho "Is it morning? Please answer yes or no."read inputcase "$input" in yes | y | Yes | YES ) echo "Good Morning.";; n* | N* ) echo "Good Afternoon.";; * ) echo "Sorry, answer not recognized.";;esacexit 0
The above code, which uses |
symbols, that is to say, merges multiple matching patterns, and uses *
wildcards; no problem, the above code works well.
&& | | Operator
The shell also supports &&
and ||
symbols, as in the C + + language, such as:
statement1 && statement2 && statement3 && ...
Executes each command from the left, and if a command returns true
, the next command to the right of it executes. If this persists until one command returns false
, or all commands in the list are executed, follow the "short circuit" rule.
statement1 || statement2 || statement3 || ...
Executes each command from the left, and if a command returns false
, the next command on its right can be executed. This continues until a command returns true
, or all commands in the list are executed.
Statement block
There are also statement blocks in the shell, which are used {}
to define a block of statements. We can put multiple statements in a block of statements to execute.
Function
function, so NB of things, how can the shell less. The structure of the definition function is as follows:
function_name(){ statements}
code example:
#!/bin/bashfoo #运行到这里,还没有定义foo函数,会报错foo() { echo "Function foo is executing."}echo "script starting"foo #输出"Function foo is executing."echo "script ended"exit 0
The script starts at the top of its own, and when it encounters a foo() {
structure, it knows that the script is defining a foo
function named. When executed to a separate foo
, the shell knows that it should execute the function just defined. After the function has been executed, foo
the script continues with the execution of the code.
When a function is called, the positional parameters (,,,, and so on) of the script are $*
[email protected]
replaced with the parameters of the $#
$1
$2
function, which is also the way we read the arguments passed to the function. These parameters revert to their previous values when the function finishes executing.
We can use local
keywords to declare local variables in shell functions, and local variables will only work within the scope of the function. In addition, the function can access other shell variables within the scope of the global scope. If a local variable has the same name as a global variable, the former overwrites the latter, but only within the scope of the function, such as the following code:
#!/bin/bashsample_text="global variable"foo(){ local sample_text="local variable" echo "Function foo is executing..." echo $sample_text}echo "script starting..."echo $sample_textfooecho "script ended..."echo $sample_textexit 0
The output is as follows:
script starting...global variableFunction foo is executing...local variablescript ended...global variable
Summarize
Finally, the first part is summed up, and the second part, in the next post will be the main summary of the shell often used in some of the commands. This is the post that summarizes some of the basics of the shell, and the next goodbye.
Jelly wanted-an original technical article to share the site.
October 28, 2014 in Shenzhen.
If you feel that the article is good, you can focus on jelly to public number, regularly push technical articles:
Linux Shell Brief Tutorial (i)