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"
以上紅色為空格,且變量兩端要加雙引號