1.第一个script,输出hello world
#!/bin/bash
echo -e "hello world"
exit 0
1) 第一行#!/bin/bash声明script使用的shell名称
2) 除了第一行的#! 其他的#,都是注释用的
3) echo输出hello world
4) exit 0 程序结束
2.将用户输入的内容打印出来
#!/bin/bash
read -p "please input your name: " firstname
echo -e "\nyour name is: $firstname"
echo 加上 -e 参数就可以将 "" 内的 \n 解析,否则会直接输出 \n
3.用户输入文件名后,根据文件名和当前时间创建新的文件
#!/bin/bash
echo -e "i will use 'touch' comman to create file."
read -p "please input your filename: " fileuser
date=$(date +%Y%m%d)
file=${fileuser}${date}
touch "$file"
4.利用test命令测试功能
判断某文件是否存在
参数:
-e 该文件名是否存在
-f 该文件是否存在且为文件
-d 该文件是否存在且为目录
-r 该文件名是否存在且具有可读权限
-w
-x
5.shell script的默认变量
$0 脚本名称
$1 第一个参数
$2 第二个参数
等等
$# 参数个数
例子
#!/bin/bash
echo "The script name is $0"
echo "Total parameter number is $#"
echo "The 1st parameter ==> $1"
6.关于if else的脚本练习
#!/bin/bash
if [ "$1" == "hello" ];then
echo "hello, how are you"
elif [ "$1" == "" ];then
echo "you must input parameters"
else
echo "the only parameter is 'hello'"
fi
if 后面的[,它的后面要由空格, ] 前要由空格
以fi 结束
7.函数function
#!/bin/bash
function print(){
echo " my name is function"
}
print
8.while循环
#!/bin/bash
i=10
while [ $i -gt 0 ]
do
echo "num is $i"
i=$(($i-1))
done
![](https://i-blog.csdnimg.cn/blog_migrate/38cbdbc4d72e5d23ef053dc871a5d5b7.png)