要用linux,不会shell 基本语法搞不来~

246 阅读1分钟

01.变量

1、环境变量

echo $PATH

2、自定义变量

hello="hello_world"
echo $hello

3、存储 Linux 命令执行结果作为变量

(2 种方式,推荐使用第二中,第一种是 ~键上面的斜点比较难识别)
files=ls -al
path=(pwd)注意点定义变量=号两边不能有空格使用变量需要加 符号

02.基本运算

1、运算符

+:加
-:减
*:乘
/:除
%:取余
==:判断是否相等
!=:不等于

:大于
=:大于或等于
<:小于
<=:小于或等于

2、整数运算(expr)

expr 10 + 3 echo \[10 + 3\] 将计算结果存储为变量2种方式 num=(expr 10 + 3) num=`expr 10 + 3`

注意点
运算符前后必须用空格
*乘必须加反斜杠转义

3、整数运算($[])

num1=100
num2=200
sum_num=$[$num1+num2]

注意点
运算符前后可以不空格
*乘不需要加转义符

4、浮点运算

num=$(echo "scale=2;10/3" | bc)

scale:保留小数的位数

将 10/3 给 bc 计算器计算,保留两位小数

03.条件选择if 后面接的是命令,其实是这个命令的退出状态码,正常退出,状态码 0,其他的就不是 0。这里意思是如果是 0 就执行 then,否则就不执行1、

if-then
if command
then 
    "执行成功"
fi

2、

if-then-else

3、

if-then-elif-else
if判断基本语法,if开头,fi结尾

#/bin/bash
  NUM='4'
  if (( $NUM > 4 ))
    then
    echo "$NUM more then 4"
  elif (( $NUM == 4 ))
    then 
    echo "$NUM 等于4" 
  else
    echo "$NUM less then 4"
  fi 

4、case 语句

case $num in
1)
  echo "num=1"
2)
  echo "num=2"
3)
  echo "num=3"
esac

04.循环

  1. for - in

    for i in list do commands done

2.C 语言风格

for (( i = 0;i <= 10;i++))
do
  commands
done

3.while 循环

while test command
do 
  echo "条件满足的时候执行这里的操作"
done

num=8
while (( $num < 10 ))
do
  echo "条件满足的时候执行这里的操作"
  echo "$num小于10"
done

4.until 循环

until test command
do 
    echo “条件不满足的时候执行”
done

说明:

  1. condition 为条件表达式,值为 false,则继续执行循环体内语句,否则跳出循环

  2. until 循环与 while 循环处理方式刚好相反

  3. 控制循环break 跳出外层循环,同 pythoncontinue 终止当前循环,进入下一个循环,同 python

    while (( 1>0 )) do echo –n “输入一个数字” read num if (( $num>10 )) then
    break else continue fi done

05.命令行参数处理

bash shell 可以根据参数位置来获取参数
通过 11 到 9 获取第 1 到第 9 个命令行参数
0shell名,如果参数超过9个,就通过0 为 shell 名,如果参数超过 9 个,就通过 {10}来获取

06.获取用户输入(read)

单个输入,指定变量接收输入的值(choice)

echo -n "yes or no(y/n)"
read choice
echo "you choice is : $choice"

单个输入,不指定变量接收输入的值,read 会将它接收到的任何数据放到特殊环境变量 REPLY 中

echo -n "yes or no(y/n)"
read
echo "you choice is : $REPLY"

多个输入

read -p "what is you name?" first second
echo first:$first
echo second:$second

上面的例子首先会输出 what is you name? 然后在本行等待用户输入,此处的 read -p 实现以上实例的 echo -n + read 不换行的效果,输入的参数用空格隔开,如果输入的值超出接收的变量个数,shell 会把剩下的值都赋值给最后一个变量。

07.超时设置

if read -t 5 -p "enter you name:"
name
then
  echo "hello $name"
else
    echo "time out"
fi

注意点

  1. 变量名一般大写
  2. 数值比较 (( 8 > 7 ))
  3. 字符串比较 【【 str1 != str2 】】
  4. test 命令只能判断以下 3 类条件数值比较
    字符串比较
    文件比较
  5. 5shell 脚本的流控制语句结束语句就是开始语句反过来写,如 if 结束语句 fi,case 结束语句 esac

数值比较
字符串比较
文件比较

8.福利领取

需要全套Linux相关shell语法大全的可以关注并私信我关键词“测试”免费领取