Shell腳本介紹
1、Shell腳本,就是利用Shell的命令解釋的功能,對一個純文本的文件進行解析,然后執行這些功能,也可以說Shell腳本就是一系列命令的集合。
2、Shell可以直接使用在win/Unix/Linux上面,並且可以調用大量系統內部的功能來解釋執行程序,如果熟練掌握Shell腳本,可以讓我們操作計算機變得更加輕松,也會節省很多時間。
3、Shell是一種腳本語言,那么,就必須有解釋器來執行這些腳本,常見的腳本解釋器有:
(1)、bash:是Linux標准默認的shell。bash由Brian Fox和Chet Ramey共同完成,是BourneAgain Shell的縮寫,內部命令一共有40個。
(2)、sh: 由Steve Bourne開發,是Bourne Shell的縮寫,sh 是Unix 標准默認的shell。
另外還有:ash、 csh、 ksh等。
常見的編程語言分為兩類:一個是編譯型語言,如:c/c++/java等,它們遠行前全部一起要經過編譯器的編譯。另一個解釋型語言,執行時,需要使用解釋器一行一行地轉換為代碼,如:awk, perl, python與shell等。
4、使用場景,能做什么
(1)、將一些復雜的命令簡單化(平時我們提交一次github代碼可能需要很多步驟,但是可以用Shell簡化成一步)
(2)、可以寫一些腳本自動實現一個工程中自動更換最新的sdk(庫)
(3)、自動打包、編譯、發布等功能
(4)、清理磁盤中空文件夾
總之一切有規律的活腳本都可以嘗試一下
編寫一個簡單的shell腳本
#!/bin/bash
# 上面中的 #! 是一種約定標記, 它可以告訴系統這個腳本需要什么樣的解釋器來執行;
echo "Hello, world!”
將以上內容保存在一個.sh格式的文件中,執行以下命令
bash test1.sh 或者 . test1.sh
最后輸出 Hello, world!
創建一個shell腳本 ,通過shell腳本當前目錄創建一個test文件夾,復制test1.sh文件到test文件夾里,進入文件夾test初始化一個npm並按照一個npm模塊,通過執行 bash test2.sh命令
#!/bin/bash
# 上面中的 #! 是一種約定標記, 它可以告訴系統這個腳本需要什么樣的解釋器來執行;
echo "test2.sh start..."
mkdir test
cp -rf test1.sh test/
cd test
npm init
npm i --save lodash
echo "test2.sh end..."
寫成一行,使用&&符號連接
mkdir test && cp -rf test1.sh test/ && cd test && npm init && npm i --save lodash
行尾使用反斜杠\使其能接着輸入其他命令,不馬上執行命令
echo "test2.sh start..."
mkdir test && \
cp -rf test1.sh test/ && \
cd test && \
npm init && \
npm i --save lodash
echo "test2.sh end..."
行尾添加反斜杠 ,作用是不馬上執行命令可接着輸入其他命令,如下
[yd@bogon:~/Documents/www/workspa/test/shell]$ mkdir test2 && \
> cd test2 && \
> npm init && \
> npm install loadsh --save
shell腳本參數傳遞,通過$0,$1,$2可以接收命令行傳遞的參數,$0 就是你寫的shell腳本本身的名字,$1 是你給你寫的shell腳本傳的第一個參數,$2 是你給你寫的shell腳本傳的第二個參數
復制以下內容到test2.sh文件中
echo "shell腳本本身的名字: $0"
echo "傳給shell的第一個參數: $1"
echo "傳給shell的第二個參數: $2”
然后 執行命令bash test2.sh 1 2,可以看到輸出結果
shell腳本本身的名字: test2.sh
傳給shell的第一個參數: 1
傳給shell的第二個參數: 2
編寫一個自動提交git的shell腳本
創建gitautopush.sh文件,將以下內容復制進去
#!/bin/bash
# 上面中的 #! 是一種約定標記, 它可以告訴系統這個腳本需要什么樣的解釋器來執行;
echo "gitautopush start..."
git add .
git commit -m $1
echo "git提交注釋:$1"
git push origin master
echo "gitautopush end..."
以上自動提交git腳本就寫好了,現在輸入以下命令執行腳本
bash gitautopush.sh 自動提交測試
控制台輸出 ,代碼已經成功提交到git服務器了
gitautopush start...
[master be8d56b] shell
3 files changed, 51 insertions(+)
create mode 100644 shelldemo/gitautopush.sh
create mode 100644 shelldemo/test1.sh
create mode 100644 shelldemo/test2.sh
git提交注釋:自動提交測試
Counting objects: 6, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (6/6), done.
Writing objects: 100% (6/6), 1.14 KiB | 1.14 MiB/s, done.
Total 6 (delta 2), reused 0 (delta 0)
remote: Resolving deltas: 100% (2/2), completed with 1 local object.
To https://github.com/fozero/frontcode.git
2e79d26..be8d56b master -> master
gitautopush end...
參考
https://www.cnblogs.com/gaosheng-221/p/6794429.html
https://www.cnblogs.com/yinheyi/p/6648242.html