#!/bin/bash
echo "第一个shell小程序"
echo "echo hello world!"
echo "====================输出环境变量path:==============="
echo $PATH
echo "===============输出当前所在目录:===============";
echo `pwd`
echo "=============输出变量=============="
myname="wanghua"
echo $myname;
echo "============将linux命令执行结果赋值给变量============"
path=$(pwd)
files=`ls -al`
echo current path:$path
echo files:$files
echo ====================基本数据类型运算=================
echo 输出10+3
expr 10 + 3
echo 输出10-3
expr 10 - 3
echo 输出10*3
expr 10 * 3
echo 输出10/3
expr 10 / 3
echo ========================将计算及结果赋值给变量===============
num1=`expr 10 + 3`
echo 输出变量num1的结果
echo $num1
echo "方括号($[])"
num1=10
num2=3
echo "1、输出num1 + num2=13:$[$num1 + $num2]"
echo "2、输出num1+num2=13:$[$num1+$num2]"
echo "=============== 麻烦的浮点运算============"
echo "先看表达式(语法)"
echo "variable=\$(echo \"options; expression\" \| bc)"
echo "表示 10/3, 保留2位小数,将结果赋值给了num, 输出3.33"
num=$(echo "scale=2;10 / 3" | bc)
echo $num
echo "本篇比较无聊,简单介绍了shell的基本运算符及其运算。shell运算主要分为整型和浮点型的运算。整型又有两种实现方式,浮点型是通过使用bash内置的计算器(bc)来实现的"
echo "==================学习shell流程控制语句 if ====================="
if test pwd
then
echo "pwd正常退出时所执行代码"
else
echo "pwd非正常退出时所执行代码 eg: pw"
fi
echo "if后面跟Linux命令,命令执行状态为if条件分支依据;fi为if的结束语句"
echo "还可以变形写出更多的else:"
echo "if command1
then
commands
elif
command2
then
command3
fi"
echo "但是上面就只能根据退出状态码判断,不能写表达式,你还让我怎么写? 我各个编程语言直接吊打你!"
echo "====================接着学习test命令=================="
echo "if test command1(条件命令)
then
commands(执行代码)
elif
command2(条件命令)
then
command3(执行代码)
fi"
echo "====================test命令高级比较(不用转义,省掉很多麻烦)=================="
echo "1、使用双小括号((数值比较))"
echo "2、使用双中括号[[字符串比较]]"
echo "数值比较2>1:"
if (( 2 > 1 ));then
echo "2大于1"
else
echo 2小于1
fi
echo "字符串比较符;=;!=;<;>;-n(判断字符串长度非0);-z(判断字符串长度为0)"
echo "字符串比较str=str2:"
str=abcd
str2=efgh
if [[ $str = $str2 ]]; then
echo "str等于str2"
else
echo "str不等于str2"
fi
echo "提示:输入命令 main test查看更多用法;"
echo "=============================接下来学习shell的循环语句================================"
echo "shell循环有3中方式 for ; while ; until"
echo "for循环有两种形式 1、for-in ; "
echo "for var in list
do
commands
done"
echo "举个例子"
for str in a b c d e
do
echo 我是:$str
done
echo "发现:字母之间使用空格隔开的,空格是由环境变量配置的,所以可以修改环境变量(IFS)改变分隔符"
echo "保存原有IFS值"
oldIfs=$IFS
echo "定义新的IFS值"
IFS=$','
list=a,b,c,d,e
list2="a b c d e"
echo "输出list:"
for var in $list
do
echo $var
done
echo "输出list2:"
for var2 in $list2
do
echo $var2
done
echo "还原IFS"
IFS=$oldIfs
echo "=========================下面学习C语言风格的for循环======================="
echo "语法for (( variable assignment ; condition ; iteration process ))"
echo "for (( i = 0; i <= 10; i++ ))
do
echo i
done"
for (( i = 0; i <= 10; i++ ))
do
echo $i
done
echo "循环控制 break 和 continue"
echo "1、break:(break 可后接数字,用于表示退出当前循环的外层的第几层循环。)"
for (( i=0; i<10; i++ ))
do
if(( i == 5 ))
then
break
fi
echo $i
done
echo "2、continue:continue表示终止当前的一次循环,进入下一次循环,注意,continue后面的语句不会执行。"
echo "continue的语法与break一样,因此,这里就不演示啦。"
for (( i=0; i<10; i++ ))
do
if(( i == 2 ))
then
continue
fi
echo $i
done
echo "注意看输出结果是没有2的"