寫第一個腳本

寫一個腳本

1.找個地方新建文件,後綴隨意,一般來說腳本的後綴是 .sh,但是我偏要把後綴寫成 .txt。我喜歡把腳本放在 ~/local 目錄裏。(我知道你沒有這個目錄,創建一下這個目錄就行啦)

mkdir ~/local
cd ~/local 請一定要運行這句話!如果不運行,那麼下面所有步驟都會出錯
touch demo.txt

2.編輯 demo.txt,內容如下:

 pwd # 確認一下當前路徑是不是 ~/local 或者 /c/Users/你的名字/local
 mkdir demo
 cd demo
 mkdir css js
 touch index.html css/style.css js/main.js
 exit

3.(Windows 用戶請跳過這一步)給 demo.txt 添加執行權限 chmod +x demo.txt

4.在任意位置執行 sh ~/local/demo.txt 即可運行此腳本

cd ~/Desktop
sh ~/local/demo.txt
你會看到當前目錄裏多出一個 demo 目錄,demo 目錄裏面還有一些文件
好了,這個 demo.txt 就是你寫出的第一個 Bash 腳本了。

5.將 ~/local 添加到 PATH 裏

cd ~/local; pwd 得到 local的絕對路徑
臨時設置 PATH
	i. 運行 export PATH="local的絕對路徑:$PATH",這句話是把 local 目錄加到 PATH 裏,注意替換 local的絕對路徑
	ii. 這時你只要運行 demo.txt 就相等於運行 sh ~/local/demo.txt 了(你可能會看到 File exists 的報錯,不用管它)
永久設置 PATH,上面的 PATH 在你重啓 Bash 之後就會失效,如果你希望 PATH 一直生效,看下面
	i. 創建 ~/.bashrc:touch ~/.bashrc
	ii. 編輯 ~/.bashrc:start ~/.bashrc
	在編輯器裏添加一行字: export PATH="local的絕對路徑:$PATH"
		a. 有些同學居然不知道 local的絕對路徑 是什麼,我真是服了,前面的都白講了
		b. 想要知道 local的絕對路徑,只需要:
		c. 進入 git bash
		d. cd ~/local
		e. pwd
		f. 打印出來的東西就是 local的絕對路徑!
	source ~/.bashrc
	之前你要運行 sh ~/local/demo.txt,現在你只需要運行 demo.txt(注意不是 demo,是 demo.txt 啊同學,幾十個同學都看成 demo 了,眼睛是不是瞎了……)就行了

6.如果你覺得 demo.txt 的後綴 .txt 沒什麼用,可以用下面的命令刪掉它

mv ~/local/demo.txt ~/local/demo
現在你只要運行 demo 就能執行該腳本了。
但是如果你沒有運行過 mv ~/local/demo.txt ~/local/demo,就必須用 demo.txt 才能執行 demo.txt(看起來是廢話,但是很多學生都沒發現)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章