1.for循环shell
for循环用于值列表中的相同命令的重复bash
#!/bin/bashide
while [ -z "$*" ]函数
do测试
echo "please give a num"this
exit 0spa
done命令行
for ((i=0;i<$1;i++))3d
dorest
((j=j+i))
done
echo $j
测试
2.bash位置参数
有两种简单的方法能够将用户输入读入bash中的变量。第一个方法是使用read提示用
户输入(使用-p选项)并将其直接存储到一个或多个变量:
交互式输入
# read -p 'Enter your first and last name: ' FIRST LAST
另外一个方法是使用位置参数来读取传递给脚本的命令行参数或选项输入。各类特殊
变量存储传递的选项编号
Bash解析的个别参数或整个原始命令行。
指定的位置参数总数:$#
位置参数自身:$0、$一、$二、$3....
全部位置参数: $@、$*
#!/bin/bash
echo $*
echo $0
echo $1
echo $2
echo $3
echo $#
测试:
3.退出状态
Linux命令完成时,将返回退出状态。成功完成程序时,将返回0的推出状态。这被bash
看成逻辑True值。非零退出状态一般表示发生了错误,而且被bash看成逻辑False值。
例如:grep的退出状态的含义:
0 – 在指定的文件中找到了模式
1 – 在指定的文件中未找到模式
>1 – 一些其余错误(没法打开文件、错误的搜索表达式等)
推出状态的值被存储在"?"中,可使用如下命令查看:
# echo $?
#!/bin/bash
while [ -z "$*" ]
do
echo "please give a num"
exit 0
done
for ((i=0;i<$1;i++))
do
((j=j+i))
done
echo $j
echo $?
测试:
4.test条件判断
test命令可用于评估bash脚本中的表达式。它评估其参数所指定的表达式,若是表达式
为true,返回零退出状态,若是表达式为false,则返回非零退出状态。test具备替代语
法,使用方括号"[]"将表达式括起来,这样更易于阅读
#!/bin/bash
while [ -z "$*" ]
do
echo "please give a varchar"
exit 0
done
[ -f "$1" ]&&echo "$1 is a file"
[ -d "$1" ]&&echo "$1 is a direction"
[ -b "$1" ]&&echo "$1 is a 设备"
[ -x "$1" ]&&echo "$1 is a 可执行文件"
[ -c "$1" ]&&echo "$1 is a char"
echo $?
测试:
5.if语句
if命令检查if后面的命令或列表的退出值。若是第一个命令评估为true/零,则运行then
以后的命令列表,直至任一else。若是第一个命令评估为false/非零,则运行else与fi之
间的命令列表(反向平写if,标记if块的结束)。
语法:if command; then command; command2; else command3; fi
水仙花数(i只能给大于99,小于1000的数)
#!/bin/bash
while [ -z "$1" ]
do
echo "please give me a num"
exit 0
done
for ((i=100;i<$1;i++))
do
let x=$i/100
m=`echo ${x%.*}`
let y=($i-m*100)/10
n=`echo ${y%.*}`
let z=$i-m*100-n*10
o=z
num1=$((m*100+n*10+o))
num2=$((m*m*m+n*n*n+o*o*o))
if [ $num1 -eq $num2 ];then
echo "水仙花数$num1"
fi
done
测试
6.case语句
case语句 :它可以把变量的内容与多个模板进行匹配,再根据成功匹配的模板去决定应该执行哪
#!/bin/bash
case $1 in
start | begin)
echo "start something"
;;
stop | end)
echo "stop something"
;;
reload | restart)
echo "restart or reload something"
;;
*)
echo "you no give me a command" esac
测试
7.expect
在shell中利用expect实现自动应答脚本
8.函数
#!/bin/bash
ACTION () {
if
[ -z "$3" ]
then
echo "please give me a userfile"
elif
[ ! -e "$3" ]
then
echo "$3 is not exist!!"
else
[ $1 "$3" ]&&echo "$2"
fi
}
ACTION -f 'this is a file' $1
ACTION -d 'this is a direction' $1
ACTION -b 'this is a 设备' $1
ACTION -c 'this is a char' $1
9.环境变量
shell和脚本使用变量来存储数据 ,有些变量能够连同它们的内容传递给子进程,这些
变量咱们称之为环境变量