Getting started with bash shell basics, the only way to learn Linux

input Output

echoIndicates to print a string; readIndicates to get user input; $used to refer to variables.

# test1.sh  bash中用#进行单行注释
echo "input your name:"
read user_name
echo "hello $user_name"

The result of its operation is

$ bash test1.sh 
input your name:    #为echo打印
laser               #为用户输入
hello laser

Assignment and calculation

bashThere is nothing special about the operators in

operator illustrate
+-×/,% Addition, subtraction, multiplication and division, remainder; support +=forms
**&&|| Power, relation and, or

However, unlike common programming languages, bashassignments and mathematical computations in (()). And inside the double brackets, you don't have to use $to refer to the variable. But outside the double brackets, when assigning a value to a variable, you need to use$

$ ((a=5+3))
$ b = $((a+3))        #双括号内是数值,需要用$
#一般在C语言中合法的表达式均可用于双括号内
$ echo $((a>b ? a:b))
11

Conditional judgment

bash, the conditional judgment [[]]is realized by passing. E.g

$ [[ 3 -eq 5 ]] #3是否等于5
$ echo $?       #$? 表示上次计算的结果
1               #在bash中,0表示真,其他表示假

Note that in bash, it 0means true. The supported conditional judgment operators are as follows

Integer comparison -eq -ne -gt -lt -ge -le
truecondition equal range left>right Left <right left >= right Left <= right
string comparison > < == !=,<> =~
truecondition left>right Left <right equal range Left matches right (regex)

Among them, the string comparison is lexicographical order.

file comparison -nt -ot -ef
truecondition Left is newer than right left is older than right left and right the same
trueCondition 2 Left exists, right does not exist Left does not exist, right exists

In addition, bash also supports the judgment of file attributes, which is necessary as far as the operating system is concerned. However, as far as programming languages ​​are concerned, this function for file interaction is advanced content, so it is placed later.

Now the key is to learn the control structure of conditional judgment. bashLike other languages, it uses the ifkeyword as the keyword and the keyword fias the end of the conditional structure. The distance is as follows

$ ((a=15))
$ ((b=20))
$ if [[ a -le b ]]; then
> echo $a   #如果a<b则打印a
> else
> echo $b   #否则打印b
> fi
15

In addition to using [[]], you can also pass testor [], but the scope of application is limited, and beginners only need to master [[]].

function

In programming languages, the importance of functions is self-evident. In bash, creating a function is also very simple, the basic format is

func(){
    
    
    # 传入参数用$1...$9表示
    return ...  #如果无返回值则不用return
}

which funccan be replaced with the name of the function. In bash, provides some built-in $parameters about the function, $1~ $9can represent the incoming parameters, when the parameter position is greater than 10, it needs to be written in a similar ${10}form.

Since the judgment expression has been explained, a recursive factorial function can be implemented below.

#!/bin/bash
fac(){
    
    
    x=$1
    if [[ ${x} -eq 1 ]];then
        echo "1"
    else
        echo "$[$x * $(fac $[$x-1])]"
    fi
}

res=$(fac $1)
echo "$1的阶乘是:${res}"

$Expressions are also used as follows

$# Number of parameters
$* show all parameters
$@ Show all parameters but use quotes and return each parameter in quotes
$$ The current process ID number of the script running
$! ID number of the last process running in the background
$- Displays the current options used by the shell, which has the same function as the set command.
$? Exit status of the last command, 0 means no error.

for loop

In bash if else, there are other caseoptions available for conditional selection in addition to . But for beginners, there is no need to be greedy, so casethe priority of learning is lowered.

The same is true for loops. Although structures such as , , , etc. are supported for, whilethey will untilbe put later for the time being. Only the most understandable C-style forloops will be explained here.

Its complete structure isfor do done

for ((i = 0 ; i <= 1000 ; i++)); do
  echo "Counter: $i"
done

Among them, (())it can also be understood as the assignment and mathematical calculation mentioned earlier. And unsurprisingly, bashZhong also supports continueand break, the former can skip the current loop, the latter can jump out of the loop.

In bash, other loop structures are also do...doneused to specify loop regions. And when keywords such as doand forother keywords are on the same line, they need to be ;separated by a semicolon.

Array and its traversal

In bash, parentheses can be used to build arrays in addition to creating local shells.

$ arr=(A B "C" D)
$ echo $arr
A
$ echo ${arr[1]}
B
$ echo ${arr[*]}    #获取全部数组元素
A B C D

Through the for...instatement, you can traverse the array, but it should be noted that the array must pass @so when it is traversed.

$ for var in "${arr[@]}"
> do
> echo $var
> done
A
B
C
D

In addition, forthere are more convenient traversal solutions for loops

$ for i in 1 2 3 4 5
> do
> echo $i
> done
1
2
3
4
5

other control statements

whileand untilare syntactically identical, but semantically the exact opposite. The former is executed until the condition is falsereached, and the latter is executed until the condition is truereached.

a=0
# 下面的例子将打印从0到10的自然数
until [[ $a -gt 10 ]]
    do
    echo $a
    a=$((a+1))
    done

Finally, basha multiple-selection statement, case...esac, is also provided, and its application logic is the switch casesame as that of , the specific example is as follows

echo 'input a number:'
read num
case $num in
    1)  echo 'you input 1'
    ;;
    2)  echo 'you input 2'
    ;;
    *)  echo 'you input others'
    ;;
esac

Among them, 1), 2) represent the situation that occurs, which ;;is equivalent breakto jumping out case.

At this point, you have mastered the bashbasic grammar as a language.

Guess you like

Origin blog.csdn.net/m0_37816922/article/details/124004496