shell脚本以 .sh为后缀,里面存放着一行行要运行的linux指令。
shell脚本第一行一定为 #!/bin/bash,表示使用bash。
shell文件举例如下:
#!/bin/bash
echo "hello shell!"
shell文件默认没有可执行权限,因此 chmod 777 myshell.sh
./myshell.sh
交互式shell
#!/bin/bash
echo "Please input your name: "
read name
echo "I have read your name" $name
read -p "Please input your name and height: " age height
echo "Your age is $age, your height is $height"
上述代码中,read用于读取变量,-p 用于输出提示信息
shell支持整型变量的运算
#!/bin/bash
echo "Please input two int nums: "
read -p "First num: " a
read -p "Second num: " b
total=$(($a + $b))
echo "$a + $b = $total"
运算表达式要用双重括号
total后的"="两边不能有空格
test命令的使用
1. 判断文件是否存在
#!/bin/bash
echo "Please input filename: "
read -p "File name: " filename
test -e $filename && echo "$filename exist!" || echo "$filename does not exist!"
2. 判断字符串是否相等
#!/bin/bash
echo "Please input two strings: "
read -p "First string: " firststr
read -p "Second string: " second
test $firststr == $secondstr && echo "Equal" || echo "Not equal"
[ ] 判断符作用类似于test,里面只能使用==或!=
#!/bin/bash
echo "Please input two strings: "
read -p "First string: " firststr
read -p "Second string: " second
[ "$firststr" == "$secondstr" ] && echo "Equal" || echo "Not equal"
以上红色为空格,且变量两端要加双引号