1.編寫個人第一個shell腳本小程序:
[root@wenhaijin /]# mkdir shell [root@wenhaijin /]# cd shell/ [root@wenhaijin shell]# vim helloworld.sh #!/bin/bash #my first shell project echo "Hello World" ~ ~ ~ ~ "helloworld.sh" [New] 4L, 56C written
注意:linux
1.#!/bin/bash標誌着如下內容是shell腳本(該行不是註釋,這是固定寫法)
2.#my first shell project是註釋shell
3.echo "Hello World"是腳本的內容,注意不要加「!」,!在腳本中有特殊含義,若是要加「!」就寫成echo 'Hello World!'小程序
2.shell腳本的執行
2.1 使用bash命令執行(不經常使用)
[root@wenhaijin shell]# bash helloworld.sh Hello World [root@wenhaijin shell]#
2.2 賦予執行權限,直接運行(通常都是經過這種方式執行)
[root@wenhaijin shell]# chmod 755 helloworld.sh [root@wenhaijin shell]# ./helloworld.sh Hello World [root@wenhaijin shell]#
3.將dos環境下的腳本轉化爲linx環境下的腳本
爲何要將dos下的腳本轉化爲linux中的腳本呢,由於dos環境和linux環境對一些隱藏字符的處理方式不同,好比linux中的回車使用$符號表示的vim
### cat -A 表示查看詳細信息,包括隱藏字符,這邊的$實際上表明的就是linux中的回車 [root@wenhaijin shell]# cat -A helloworld.sh #!/bin/bash$ #my first shell project$ $ echo "Hello World"$
而在dos環境中,回車是用^M$表示,linux並不認識bash
[root@wenhaijin shell]# unix2dos helloworld.sh unix2dos: converting file helloworld.sh to DOS format ... [root@wenhaijin shell]# cat -A helloworld.sh #!/bin/bash^M$ #my first shell project^M$ ^M$ echo "Hello World"^M$ [root@wenhaijin shell]# ./helloworld.sh -bash: ./helloworld.sh: /bin/bash^M: bad interpreter: No such file or directory [root@wenhaijin shell]#
若linux系統中尚未dos2unix命令,可經過yum或者rpm包進行安裝url
[root@wenhaijin shell]# yum -y install dos2unix Loaded plugins: security base | 3.7 kB 00:00 epel | 4.3 kB 00:00 epel/primary_db | 5.9 MB 00:01 extras | 3.4 kB 00:00 extras/primary_db | 37 kB 00:00 updates | 3.4 kB 00:00 updates/primary_db | 5.4 MB 00:00 Setting up Install Process Resolving Dependencies --> Running transaction check ---> Package dos2unix.x86_64 0:3.1-37.el6 will be installed --> Finished Dependency Resolution Dependencies Resolved ================================================================================ Package Arch Version Repository Size ================================================================================ Installing: dos2unix x86_64 3.1-37.el6 base 16 k Transaction Summary ================================================================================ Install 1 Package(s) Total download size: 16 k Installed size: 18 k Downloading Packages: dos2unix-3.1-37.el6.x86_64.rpm | 16 kB 00:00 Running rpm_check_debug Running Transaction Test Transaction Test Succeeded Running Transaction Installing : dos2unix-3.1-37.el6.x86_64 1/1 Verifying : dos2unix-3.1-37.el6.x86_64 1/1 Installed: dos2unix.x86_64 0:3.1-37.el6 Complete!
而後執行dos2unix命令將腳本轉化爲linux環境下的兼容腳本spa
[root@wenhaijin shell]# dos2unix helloworld.sh dos2unix: converting file helloworld.sh to UNIX format ... [root@wenhaijin shell]# ./helloworld.sh Hello World [root@wenhaijin shell]#
4.知識拓展,執行一個shell腳本實現俄羅斯方塊的小例子
[root@wenhaijin shell]# chmod 755 Tetris.sh [root@wenhaijin shell]# ./Tetris.sh
這個小遊戲的下載地址:http://pan.baidu.com/s/1c1Npu4g.net