Shell command and programming basics

1. About Shell

  • Program written in C language
  • command language/programming language

Create steps:

  1. Create a .sh file
  2. write shell code
  3. Execute the shell script (the script must have executable permissions): chmod +x

2. Variables

define before use

        zjc_name="zjc"

        echo $zjc_name

Variable name specification:

  • There can be no spaces around the equal sign after the variable name
  • Names can only use English letters, numbers and underscores, and the first character cannot start with a number
  • no spaces in between
  • Cannot use punctuation
  • Keywords in bash cannot be used (help command to view reserved keywords)
#!/bin/bash
str='hello world';
echo $str

Double quotes can identify variables and realize escaping

Single quotes do not recognize variables and can only be output as they are

2.1 Read-only variables

#!/bin/bash
a=10
readonly a
a=20
echo $a

2.2 Accept user input

read -p prompt information variable name

#!/bin/bash
read -p '请输入需要创建的文件路径:' filepath
touch $filepath
echo '文件创建成功!'
ls -l $filepath

2.3 Delete variables

unset variable name

#!/bin/bash
b=20
echo $b
unset b
echo $b

3. Operators

3.1 Arithmetic operators

#!/bin/bash
val=`expr 2 + 2`
echo "两数之和为:$val"

 There must be a space between the expression and the operator

The complete expression should be enclosed by ` ` (below the ESC key)

a=10
b=20

echo "a=$a"
echo "b=$b"

echo ''
echo 'a + b = ' `expr $a + $b`
echo 'a - b = ' `expr $a - $b`
echo 'a * b = ' `expr $a \* $b`
echo 'b / a = ' `expr $b / $a`
echo 'b % a = ' `expr $b % $a`

if [ $a == $b ]
then
        echo 'a等于b'
else
        echo 'a不等于b'
fi      

3.2 Logical operators

 ! Not operation, [! false] returns true

-o OR operation, if an expression is ture, return ture

-a AND operation. Both expressions are true

#!/bin/bash
a=10
b=20

if [ ifalse ]
then 
    echo '真'
fi

if [ $a -lt 20 -o $b -gt 100]
then
    echo '真'
fi

if [ $a -lt 20 -a $b -gt 100]
then
    echo '真'
else 
    echo ‘假’
fi

Guess you like

Origin blog.csdn.net/weixin_46267139/article/details/131182622