Linux学习笔记04:Shell基础编程
1.Shell介绍
- 文本文件,通常以.sh结尾,存放Linux命令的集合,能被Shell解释执行
- 组成:一段Linux命令、Shell命令、控制语句和注释语句等。
- 第一行:
注释行:#开头 - 变量:命名:以字母下划线开头,后面可以跟字母下划线和数字,区分大小写。
等号左右不能有空格。
分类:分为环境变量和本地变量。
本地变量:只能在创建他们的shell程序中可用。环境变量则是所有用户进程中可用,需要大写。 - 位置参量:
从命令行接收参数,跟在脚本后面用空格隔开的每个字符串。在shell文件中用$1,$2……表示。
$#表示传了多少个参数。
$*以单个字符串显示所有参数。
$?显示前面最后一个命令的状态码,除了0都是不正常。 - shell的执行:
- 数组:
- 判断:
- if语句:
if (表达式) ;then
语句 1
else
语句 2
fi
#! /bin/bash
#auto if test
#by authors zgs 2020
DIR=/tmp/20200604
if [ ! -d $DIR ];then
mkdir -p $DIR
echo -e "\033[32mThis $DIR Create success.\033[0m"
else
echo -e "\033[32mThis $DIR is exist, please exit.\033[0m"
fi
多个条件判断:
#! /bin/bash
#auto test scores
#by authors zgs 2020
scores=$1
if [ -z $scores ];then
echo "usage:{$0 60|80}"
exit
fi
if [[ $scores -gt 85 ]]; then
echo "very good!";
elif [[ $scores -gt 75 ]]; then
echo "good!";
elif [[ $scores -gt 60 ]]; then
echo "pass!";
else
echo "no pass!"
fi
- for循环
for 变量 in 字符串
do
语句 1
done
#!/bin/bash
#auto sum 1 100
j=0
for ((i=1;i<=100;i++))
do
j=`expr $i + $j`
done
echo $j
- while循环:
while 条件语句
do
语句 1
done
#!/bin/sh
i=1;
while [[ $i -lt 10 ]];do
echo $i;
((i++));
done;