Shell programming (writing, execution, shell variables, parameter passing, strings, operator usage)

Come and get to know

Shell is a program written in C language, through which users can access operating system kernel services.

Shell is both a command language and a programming language.

Shell script is a script program written for the shell. Shell programming generally refers to shell scripting, not to developing the shell itself.

Shell programming is the same as java and php programming, as long as there is a text editor that can write code and a script interpreter that can interpret and execute.

Bash is widely used in everyday work due to its ease of use and free cost. At the same time, Bash is also the default shell for most Linux systems.

Directory

shell interpreter

Create a new shell file

Write code

execute shell script

The first

the second

third

shell variable

define variables

use variables

example

explain

redefine variable

delete variable

shell string

single quote definition

double quote definition

Other string operations

get string length

extract substring

find substring

shell passing parameters

Parameter handling

test

Shell arithmetic operators

small test

Common Arithmetic Operators

test


shell interpreter

Java needs virtual machine interpreter, and shell script also needs interpreter

Let’s enter the command in Linux to check it first:

cat /etc/shells

Let’s write a shell script:

New shell file

Write Code

#!/bin/bash

echo 'hello world'

#! Is a conventional mark, and it is precisely because there are different shells, so we tell the system what interpreter this script needs to execute, that is, which shell to use.

The echo command is used to output text to the window.

Execute shell script

We used three methods to implement

First Type

The simplest specified directory execution

What is the relationship between bash and sh?

Answer: sh is a shortcut for bash

Second type

Simplified method of method 1

Why /bin/ can be omitted

Answer: Because the /bin/ directory is added to the PATH environment variable, /bin can be omitted when using /bin/sh and other similar commands

The third type

Prompted that the permissions are not enough, increase the permissions

chmod 755 hello.sh

shell variables

Define variables

In shell scripts, when defining variables,

  • Variable names without the dollar sign $
  • There can be no spaces between the variable name and the equals sign
  • The name can only use English letters, numbers and underscores, and the first character cannot start with a number.
  • There can be no spaces in between, you can use underscore _.
  • Punctuation marks are not allowed.
  • Keywords in bash cannot be used (use the help command to view reserved keywords).

For example:

your_name="haohao"

Use variables

To use a defined variable, just add a dollar sign before the variable name

Instance

my_name="haohao"

echo $my_name

echo ${my_name}

Explain

The curly braces outside the variable name are optional, you can add them or not, and the curly braces are added to help the interpreter recognize the boundaries of variables

For example:

skill="good"

echo "I am a ${skill}boy"

If the braces are not added, the interpreter will recognize $skillboy as a variable (its value is empty), and the code execution result will not be what we expect.

It is recommended to add curly braces to all variables, which is a good programming practice

Redefining variables

Since it is a variable, it is a variable quantity

your_name="tom"
echo $your_name
your_name="cat"
echo $your_name

Variables can be reassigned to change

Notice

Dollar signs are not added when changing variables, and dollar signs are added when variables are used.

Delete variable

unset variable_name
#!/bin/sh
name="haohao"
unset name
echo $name

The above code will not produce any output

shell string

String is the most commonly used and most useful data type in shell programming (except for numbers and strings, there are no other types that are easy to use). Strings can use single quotes, double quotes, or no quotes.

Single quote definition

  • Any character in the single quote will be output as it is, and the variable in the single quote string is invalid;
  • A single single quotation mark cannot appear in a single quotation mark string (even after using an escape character for the single quotation mark), but it can appear in pairs and used as a string concatenation .
skill='boy'

str='I am a $skill'

echo $str

Double quote definition

  • There can be variables in double quotes
  • Escape characters can appear in double quotes
skill='boy'

str="I am a $skill"

echo $str

Other String Operations

Get String Length

skill='java'

echo ${skill} # output result: java

echo ${#skill} # output result: 4

expr length "python" #Output result: 6

Extract substring

str="I am goot at java"

echo ${str:2} # The output result is: am goot at java Intercept from the second character to the end

echo ${str:2:2} # The output result is: am intercepts from the second character, and intercepts 2 characters

Find Substring

#Find the position of character a or m (whichever letter appears first is calculated):

str="I am goot at $skill"
echo `expr index "$str" am` # output is: 3

or:
expr index "iamlilei" am #Output result: 2 returns the position where the CHARS string is found in STRING; otherwise, returns 0

Attention

In the script above, ` is a backtick (below Esc), not a single quote ‘, don’t get it wrong

shell passing parameters

We can pass parameters to the script when executing the shell script. The format of getting parameters in the script is: $n

vim param.sh

#!/bin/bash

echo "Shell pass parameter instance!";

echo "executed file name: $0";

echo "The first parameter is: $1";

echo "The second parameter is: $2";

echo "The third parameter is: $3";
chmod 755 param.sh

$ ./param.sh 1 2 3

parameter handling

In addition, there are several special characters used to process parameters

$#

The number of arguments passed to the script

$*

Displays all arguments passed to the script as a single string. Such as "$*"

When enclosed with “””, start with "$1 $2 … $n"

Output all parameters in the form of .

$$

The current process ID number the script is running under

$!

The ID number of the last process running in the background

$@

with $*

Same, but use quotes and return each argument in quotes. Such as "$@"

When enclosed with “””, start with "$1" "$2" … "$n"

Output all parameters in the form of .

$-

Displays the current options used by the shell, which has the same function as the set command.

$?

Display the exit status of the last command. 0 means no errors, any other value indicates errors.

test

#!/bin/bash

echo "Shell pass parameter instance!";

echo "executed file name: $0";

echo "The first parameter is: $1";

echo "The second parameter is: $2";

echo "The third parameter is: $3";


echo "The number of parameters is: $#";

echo "Passed parameters are displayed as a string: $*";

Assuming that three parameters 1, 2, and 3 are written when the script is running, then ” * ” is equivalent to “1 2 3” (one parameter is passed), and “@” is equivalent to \ “1” “2” “3” (three parameters passed)

Shell arithmetic operators

Shell, like other programming, supports include: arithmetic, relational, Boolean, string and other operators.

Native bash does not support simple math operations, but can be implemented with other commands, such as expr.

expr is an expression calculation tool, which can complete the evaluation operation of expressions.

Small test

val=`expr 2 + 2`
echo $val

Attention

There must be a space between the expression and the operator, for example 2 + 2 is wrong, it must be written as 2 + 2

The complete expression should be enclosed by `, note that it is not a single quote, it is under the Esc key.

Common arithmetic operators

Suppose variable a is 10 and variable b is 20

Operator

Description

Example

+

addition

expr $a + $b

The result is 30.

subtraction

expr $a - $b

The result is -10.

*

multiplication

expr $a * $b

The result is 200.

/

division

expr $b / $a

The result is 2.

%

Take the remainder

expr $b % $a

The result is 0.

=

assignment

a=$b

will assign the value of variable b to a.

==

equal. Used to compare two numbers and return true if they are the same.

[ $a == $b ]

returns false.

!=

not equal. Used to compare two numbers and return true if they are not the same.

[ $a != $b ]

returns true.

test

#!/bin/bash

a=4

b=20

# addition operation

each expr $a + $b

# subtraction operation

echo expr $a - $b

#Multiplication operation, note that a backslash is required in front of the * sign

echo expr $a \* $b

# division operation

echo $a / $b



In addition, arithmetic operations can also be performed through (()), $(()), $[].



 ((a + + ))

echo "a = $a"

c=$((a + b))

d=$[a + b]

echo "c = $c"

echo "d = $d"

————————————–

Welcome to like, collect, comment and exchange~

Reprint please indicate the source