Introduction to Bash Basic Grammar (Part 2)

Introduction to Bash Basic Grammar (Part 2)

0X00 Foreword

Last time we talked about bash mathematics, and today we will take out the rest.
They are all basic things, I hope you can support more.
Still the old rules, let me hang up the first article:
Introduction to Bash Basic Grammar (Part 1)

0X10 Bash language parameters

We know that when running some C++ or java code, some need to enter some parameters.

So is there any parameter setting for our Bash?

The answer is: yes

We can call our script file like this:

./variable.sh Parameter 1 Parameter 2 Parameter 3…

So the question is how do we accept it in the code?

Simply beyond your expectation, haha

  • $#: Contains the number of parameters.
  • $0: contains the name of the script being run (variable.sh in our example).
  • $1: Contains the first parameter.
  • $2: Contains the second parameter.
  • $8: Contains the eighth parameter.
    ...And
    so on.

Here is an example:

#! /bin/bash
echo -e "There are $# students.\n"
echo "They are $1,$2 and $3."

Insert picture description here

0X20 array of Bash language

Bash also supports arrays

We can declare the following array

array=('value0' 'value1' 'value2')

If you want to access the content, you can also directly subscript access:

${array[2]}

But need to pay attention:

Like most programming languages, the index of the array in Shell basically starts from 0 instead of 1. > Therefore, the number (subscript) of the first element is 0, the subscript of the second element is 1, and so on.
However, not all array subscripts of Shell languages ​​start from 0, and many array subscripts of Shell languages ​​(such as Csh, Tcsh, Zsh, etc.) start from 1.

 也可以单独给数组的元素赋值,例如:
array[3]='value3'

Examples:

#!/bin/bash

array=('value0' 'value1' 'value2')
array[5]='value5'
echo ${array[1]}

Result:
Insert picture description here
You can see that one thing is different from our usual:
the element numbers of the array do not need to be continuous

We can skip some serial numbers

You can also display all the element values ​​in the array at one time, you need to use wildcards *(asterisks)

#!/bin/bash

array=('value0' 'value1' 'value2')
array[5]='value5'
echo ${array[*]}

Insert picture description here

0X30 Conditional statement in Bash language

Okay, well, we finally come to the conditional statement

Don’t say much, just start talking

1. If: the simplest condition

In Bash, the format of the if statement is like this:

if [conditional test]
then

fi

以 if 的倒装 fi 作为结束,Bash果然特立独行

**注意!!!**

Square brackets []in the 条件测试sides must be a space. Cannot [test]be written as[ test ]

We have another way of writing:

if [conditional test]; then

fi

来看一个例子:
#!/bin/bash
# condition.sh
name="Enming"

if [ $name = "Enming" ]
then
   echo "Hello $name !"
fi

Insert picture description here

As can be seen from the above example, our if condition is relatively easy to understand, but it should also be noted:

In the Shell language, "equal to" is represented by an equal sign (=)

2. If else: conditional branch

The logic of if and else is as follows:

if [conditional test]
then
do this
else
do that
fi

It is easier to understand by direct examples:

#!/bin/bash

name1="Enming"
name2="Oscar"

if [ $name1 = $name2 ]
then
    echo "You two have the same name !"
else
    echo "You two have different names !"
fi

The result is not posted anymore, you can try it yourself

Of course, there elif's the use of

The usage is like this:

if [condition test 1]
then
do things 1
elif [condition test 2]
then
do things 2
elif [condition test 3]
then
do things 3
else
do other things
fi

这使用还是简单的,只要稍微有一点编程基础

3. Case condition selection

Bash also supports case selection.
Needless to say, you can understand what you just have with an example.

#!/bin/bash

case $1 in
    "Matthew")
        echo "Hello Matthew !"
        ;;
    "Mark")
        echo "Hello Mark !"
        ;;
    "Luke")
        echo "Hello Luke !"
        ;;
    "John")
        echo "Hello John !"
        ;;
    *)
        echo "Sorry, I do not know you."
        ;;
esac

The end is also esac, hahaha is magical
and you can see the ;;symbol, which is actually equivalent to the break of C language

0X40 Loop Statement in Bash Language

After the condition is the loop, the basic routines of learning general language

1. The while loop

The loop judgment logic of while is like this:

while [conditional test]
do
do something
done

It's finally not the flip end! Probably elihw looks too strange 2333

Of course, you can still doput up

while [conditional test]; do
do something
done

Let's look at an example:

#!/bin/bash

while [ -z $response ] || [ $response != 'yes' ]
do
    read -p 'Say yes : ' response
done

Execution result:
Insert picture description here
The judgment condition of while is

  • Is response empty:-z $response
  • Is response not equal to'yes':$response != 'yes'

Regarding the judgment conditions in bash, I will sort it out, and then put the link at the end, students who are interested can take a look

2, until loop

We know that in general programming languages, if there is a loop while, there will be a corresponding do...while

Bash is also indispensable, but the key words are——until

Indicates that the statement is executed first, and then judged

For example:

#!/bin/bash

until [ "$response" = 'yes' ]
do
    read -p 'Say yes : ' response
done

The effect is the same as before

3. For loops
Speaking of loops, of course the for loops are indispensable

The for loop of bash is a bit different from C, C++, etc., but it is a bit similar to python

The basic logic is as follows:

for variable in'value 1''value 2''value 3'…'value
n'do
do something
done

Let's give an example:

#!/bin/bash

for animal in 'dog' 'cat' 'pig'
do
    echo "Animal being analyzed : $animal" 
done

The results are as follows:
Insert picture description here
see the loop traversing the above variables

The value list of the for loop does not have to be defined in the code, we can also use a variable, as follows:

#!/bin/bash

listfile=`ls`

for file in $listfile
do
    echo "File found : $file" 
done

Backticks are used here, the above loop will print out the files in the current directory

Or use variables directly:

#!/bin/bash

for file in `ls`
do
    echo "File found : $file"
done

Okay, now there are people asking questions. If you want to specify the number of loops like a normal for loop, what should you do?
Okay, look below:

#!/bin/bash

for i in `seq 1 10`
do
    echo $i
done

Insert picture description here
Cycle print 1 to 10

Satisfied now

If you are not satisfied, look again

What if I want to jump in a loop, such as 1 3 5 with intervals?
it is also fine!

#!/bin/bash

for i in `seq 1 2 10`
do
    echo $i
done

Finished, perfect

0X40 Bash language function

Finally, finally came to the last part-function.
I believe everyone is already tired, and I am also tired. Finally, everyone stick to it! Let's get straight to the point

1. The definition of the function

The function of Bash is defined as:

Function name () { function body }

or:

function function name { function body }

requires attention:

There is no parameter in the parentheses following the function name, which is very different from other programming languages

We still need examples to understand:

#!/bin/bash

print_something () {
    
    
    echo "Hello, I am a function"
}

print_something
print_something

Insert picture description here

2. Parameter transfer

Since parameters cannot be written in function parentheses, how can we pass parameters?

In fact, as long as you can think of the previous parameter transfer, you probably know

Yes, the parameters of the transfer function is $1, $2,$3

Here is an example:

#!/bin/bash

print_something () {
    
    
    echo Hello $1
}

print_something Matthew
print_something Mark
print_something Luke
print_something John

The results are as follows:
Insert picture description here

Everyone should understand after reading this, it's exactly the same as what I said before

3.
The function of the return value Shell can return a status, which is similar to that when a program or command exits, there will be an exit status, indicating whether it is successful

Shell function to return status, also use the return keyword

example:

#!/bin/bash

print_something () {
    
    
    echo Hello $1
    return 1
}

print_something Luke
print_something John
echo Return value of previous function is $?
  • Line 5: The returned status does not have to be hard-coded (such as 1 in the above example), but can also be a variable.
  • Line 10: The variable $? contains the return status of the previous command or function.

Insert picture description here

If you really want the function to return a value (for example, a calculated value), then you can also use the result of the command.

as follows:

#!/bin/bash

lines_in_file () {
    
    
    cat $1 | wc -l
}

line_num=$(lines_in_file $1)

echo The file $1 has $line_num lines

Suppose there is a test_file file, you can count the number of lines in it and return
Insert picture description here

0X50 Afterword

Alright, alright, finally the code is over!
It's just some basic things, I didn't expect so much water.
Of course, I also refer to Oscar 's column, which is really good! Wait for the link, you can check it out~

The command and parameters commonly used in shell conditions test are also given later. Those who are interested can check it out~

Then, bye everyone~

Related:
Introduction to Bash Basic Grammar (Part 1)
Commonly used conditional test commands and parameters of shell
———————————————————————————————— ———————————————————
Reference: Linux Command Line and Shell Script Programming Encyclopedia

Guess you like

Origin blog.csdn.net/rjszz1314/article/details/104481628