一、什麼是Shell腳本?
Shell腳本是一種程序設計語言,用來與操作系統交互。Shell,即命令行解釋器,是用戶與操作系統交互的一種方式。通過Shell腳本,我們可以編寫一系列的命令,實現自動化任務。
Shell腳本通常以.sh結尾,可以使用任何文本編輯器編寫。在Linux系統中,可以通過chmod命令將.sh文件賦予運行許可權,並通過./腳本名執行。
二、Shell腳本的常用命令
1、echo命令
#!/bin/bash
echo "Hello, world!"
執行結果:
Hello, world!
2、if語句
#!/bin/bash
a=10
b=20
if [ $a -gt $b ]
then
echo "a 大於 b"
else
echo "a 小於 b"
fi
執行結果:
a 小於 b
3、for循環
#!/bin/bash
for i in {1..5}
do
echo "Number is $i"
done
執行結果:
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
三、Shell腳本的變數和參數
1、定義變數
#!/bin/bash
name="Shell"
echo $name
執行結果:
Shell
2、傳遞參數
#!/bin/bash
echo "第一個參數為$1"
echo "第二個參數為$2"
echo "第三個參數為$3"
執行命令:
./test.sh apple orange banana
執行結果:
第一個參數為apple
第二個參數為orange
第三個參數為banana
四、Shell腳本的函數
1、定義和調用函數
#!/bin/bash
function hello {
echo "Hello, $1!"
}
hello "world"
hello "tom"
執行結果:
Hello, world!
Hello, tom!
2、帶有返回值的函數
#!/bin/bash
function sum {
local a=$1
local b=$2
local c=$(($a + $b))
echo $c
}
result=$(sum 10 20)
echo "10 + 20 = $result"
執行結果:
10 + 20 = 30
五、Shell腳本的文件操作
1、創建文件並寫入內容
#!/bin/bash
echo "This is a test file." > test.txt
執行命令:
./test.sh
執行結果:
生成一個test.txt文件,內容為「This is a test file.」
2、讀取文件內容
#!/bin/bash
while read line
do
echo "$line"
done < test.txt
執行結果:
This is a test file.
3、刪除文件
#!/bin/bash
rm test.txt
執行命令:
./test.sh
執行結果:
刪除test.txt文件
六、Shell腳本的流程式控制制
1、case語句
#!/bin/bash
echo "請輸入1~4之間的數字:"
read num
case $num in
1)
echo "第一項被選擇"
;;
2)
echo "第二項被選擇"
;;
3)
echo "第三項被選擇"
;;
4)
echo "第四項被選擇"
;;
*)
echo "請輸入正確的數字"
;;
esac
2、while循環
#!/bin/bash
count=0
while [ $count -le 5 ]
do
echo "Count is $count"
count=$((count + 1))
done
執行結果:
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4
Count is 5
3、until循環
#!/bin/bash
i=0
until [ $i -ge 5 ]
do
echo "Number is $i"
i=$((i + 1))
done
執行結果:
Number is 0
Number is 1
Number is 2
Number is 3
Number is 4
七、Shell腳本的其他應用
1、調用其他腳本文件
#!/bin/bash
source script.sh
2、使用awk處理文本
#!/bin/bash
cat test.txt | awk '{print $1}'
執行結果:
This
3、使用sed替換文本
#!/bin/bash
cat test.txt | sed 's/test/demo/g'
執行結果:
This is a demo file.
八、總結
通過本文的介紹,我們學習了Shell腳本的基本語法和常用命令,以及在文件操作、流程式控制制、函數等方面的應用。Shell腳本不僅可以簡化我們的工作,還可以提高效率,是Linux系統常用的編程語言之一。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/227656.html