shell 脚本基础学习
shell脚本
简单了解来说就是 将多条命令放到一个文件里,扩展名为 .sh
运行第一个shell脚本
#!bin/bash
echo "hello,world"
交互式shell脚本
#!/bin/bash
echo "please input name:"read name
echo "your name :" $name
#!/bin/bash
read -p "Please input your age and height :" age height
echo "your age = $age , your height = $height "
shell脚本的数值计算
#!/bin/bash
echo "Please input two number"
read -p "Please input the first num" first
read -p "Please input the second num" secondtotal=$(($first+$second)) //一定要注意这里 total 后面不要有空格,会报错echo $total
shell脚本的test
#!/bin/bash
echo "Please input two number"
read -p "Please input the first filename" file1
test -e $file1 && echo "$file1 is exist" || echo "$file1 is not exist"
注意这里的 && 和 || 用法不是与和或,这里是 这个文件存在,输出文件存在;若这个文件不存在,输出文件不存在
shell脚本的参数列表
!/bin/bash
echo "file name:" $0 //表示当前shell文件就是 $0
echo "total canshu:" $# //表示总的参数
echo "total context:" $@ //表示全部内容
echo "first canshu:" $1 //表示第一个参数
echo "second canshu" $2 // 表示第二个参数
shell 脚本的条件判断
#!/bin/bash
read -p "Please input(Y/N)" valueif [ "$value" == "Y" ] || [ "$value" == "y" ]; thenecho "You are sucessful"exit 0
fiif [ "$value" == "N" ] || [ "$value" == "n" ]; thenecho "You are failure!"exit 0fi
用case的方法
!/bin/bash
case $1 in"a")echo "The text is:a";;"b")echo "The text is:b";;"c")echo "The text is:c";;
esac
shell传参数
#!/bin/bash
print()
{echo "canshu1:" $1echo "canshu2:" $2}print a b //注意这里直接写就好了
shell 循环
while循环写法
#!/bin/bash
while [ "$value" != "c" ]
doread -p "Please input the thing:" valuedone
echo "STOP!"
for循环写法
#!/bin/bash
read -p "Please input a number to arrive destination :" num
sum=0
for((i=1;i<=num;i++))
dosum=$(($sum+$i))
doneecho $sum