Linux Shell 指令碼攻略閱讀筆記第1章 小試牛刀

來源:互聯網
上載者:User

標籤:linux   shell   指令碼   終端   bash   

一、簡介

1.Bash(Bourne Again Shell),目前大多數GNU/Linux系統預設的shell環境。

   命令都是在shell終端中輸入並執行。開啟終端後,提示符的形式:[email protected]$       或    [email protected] #     ($表示普通使用者,#表示管理使用者root)

2.shell指令碼是一個以#!(shebang)起始的文字檔,如下:   #!/bin/bash

shebang是一個文本行,其中#!位於解譯器路徑之前。/bin/bash是Bash的解譯器命令路徑。

3.兩種運行指令碼的方式。

   一種是將指令碼作為bash到命令列參數

[email protected]:~/lssc/chpt1$ bash test_script.sh hello,world
   另一種是授予指令碼執行許可權,將其變為可執行檔。chmod a+x script.sh

[email protected]:~/lssc/chpt1$ chmod a+x test_script.sh [email protected]:~/lssc/chpt1$ ./test_script.sh hello,world

核心會讀取指令碼的首行,注意到shebang為#! /bin/bash。它識別出/bin/bash,並在內部像這樣執行該指令碼:$  /bin/bash test_script.sh

其中,test_script.sh檔案內容如下:

#!/bin/bashecho hello,world
4.~表示主目錄,通常是/home/user,其中user是使用者名稱;若是root使用者,則為/root。

5.登入shell是登入主機後獲得的那個shell。如果是登入圖形介面環境如GNOME、KDE後開啟了一個shell,就不是登入shell。

6.Bash中,每個命令或命令序列是以分號或分行符號來分隔。#指明注釋的開始,延續到行尾。如 $  cmd1  ;  cmd2  等同於 $  cmd1  $  cmd2

二、終端列印

終端是互動式工具,可以通過它與shell環境進行互動。
1.echo.預設在每次調用後添加一個分行符號。-n 忽略結尾分行符號。

2.echo的三種形式列印:直接列印、單引號、雙引號

[email protected]:~/lssc/chpt1$ echo "Welcome to Bash"Welcome to Bash[email protected]:~/lssc/chpt1$ echo Welcome to BashWelcome to Bash[email protected]:~/lssc/chpt1$ echo 'Welcome to Bash'Welcome to Bash
三種方法的副作用:

直接列印:不能顯示文本中的分號——分號在Bash中是命令定界符。echo hello;hello被認為是兩個命令echo hello和hello。

單引號:變數替換在單引號中無效。

雙引號:不能列印歎號!。或將其轉義,\!。確切地說,歎號在末尾、或者歎號後沒有空格,則不能正常列印。如下面測試,可以看到,歎號後面有空格時還是可以列印的。

[email protected]:~/lssc/chpt1$ echo "Hello world !"bash: !": event not found[email protected]:~/lssc/chpt1$ echo "cannot include exclamation - ! within"cannot include exclamation - ! within[email protected]:~/lssc/chpt1$ echo "c!c"bash: !c": event not found[email protected]:~/lssc/chpt1$ echo "c ! c"c ! c[email protected]:~/lssc/chpt1$ echo "c! c"c! c[email protected]:~/lssc/chpt1$ echo "c !c"bash: !c": event not found

3.printf.無自動換行符。參數類似於C語言,參數以空格分隔。如下:

#!/bin/bash#檔案名稱:printf.shprintf "%-5s %-10s %-4s\n" No Name   Markprintf "%-5s %-10s %-4.2f\n" 1 Sarath 80.3456printf "%-5s %-10s %-4.2f\n" 2 James 90.9989printf "%-5s %-10s %-4.2f\n" 3 Jeff 77.564
運行顯示:

[email protected]:~/lssc/chpt1$ bash printf.sh No    Name       Mark1     Sarath     80.352     James      91.003     Jeff       77.56





Linux Shell 指令碼攻略閱讀筆記第1章 小試牛刀

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.