首先我們了解最基礎的,輸出hello world!。
1.echo 輸出命令
[root@linux-study ~]echo [選項][輸出內容]
選項: -e: 支援反斜線控制的字元轉換
[root@linux-study ~]# echo "hello word!"
bash: !": event not found --!在shell中有特殊作用。
[root@linux-study ~]# echo "hello word"
hello word
[root@linux-study ~]# echo 'hello world!' --如果是一定要使用!,可以取消它的特殊作用。
hello world!
選項的各項作用如下:
\\ 輸出\本身,其實也就是取消\後面的特殊符號
\a 輸出警告音
\b 退格鍵,也就是向左刪除鍵
\c 取消輸出行末的換行符。和「-n」選項一致
\e escape鍵
\f 換頁符
\n 換行符
\r 回車鍵
\t 製表符,也就是tab鍵
\v 垂直製表符
\0nnn 按照八進位制ascii碼表輸出字元。其中0位數字零,nnn是三位八進位制數
\xhh 按照十六進製制ascii碼表輸出字元。其中hh是兩位十六進製制數
舉例說明如下:
[root@linux-study ~]# echo "abc"
abc[root@linux-study ~]# echo -e "ab\bc" --\b刪除一格
ac----------------
[root@linux-study ~]# echo -e "a\tb\tc\nd\te\tf"
a b c
d e f
----------------
[root@linux-study ~]# echo -e "\e[1;31m abcd \e[0m"
abcd
這裡是帶顏色字元輸出。支援的格式是\e[1; 開頭,\2[0m結束。支援的顏色格式有如下:
30m=黑色,31m=紅色,32m=綠色,33m=黃色,34m=藍色,35m=洋紅,36m=青色,37m=白色
----------------
2.第乙個指令碼
root@linux-study ~]# vi
#!/bin/bash --一般情況下#開頭的是注釋語句,但是這裡的不是,這裡標示以下寫的是shell程式,當然也可以不寫,但巢狀其他語句時會報錯,所以,以後注意,寫shell時需要表明這是乙個shell程式。
#the first progtam
#author:loushen (e-mail:[email protected])
#輸出一段文字
echo -e "this is my first program that i studied shell!"
執行指令碼
[root@linux-study my-study]# sh hello.sh
this is my first program that studied shell
注意:乙個程式,良好的注釋是必要的。
3.指令碼執行
(1)賦予執行許可權,直接執行
chmod 755 hello.sh
./hello.sh --這種方式需要有執行許可權
(2)通過bash呼叫執行指令碼
bash hello.sh --這個也可以簡寫成sh hello.sh,使用bash hello.sh方式執行,不需要賦予執行許可權也可以,當然如果檔案不屬於你就不行了
---------------------
[root@linux-study my-study]# ./hello.sh
bash: ./hello.sh: /bin/bash: bad interpreter: no such file or directory
可能會報這個錯誤,原因有多種,舉例其中兩種:
(1)可能該檔案是在windows中編譯的,而windows中的換行符合linux的換行符不一樣導致的。
(2)可能是沒寫明是#!/bin/bash導致的。
cat -a hello.sh --可以檢視隱藏字元,可以了解下linux和windows的隱藏換行符的不同
[root@linux-study my-study]# cat -a hello.sh --linux本地編譯的
#!/bin/bash$
#this is my first program.$
#author:loushen$
echo -e "this is my first program,hello world!"$
[root@linux-study my-study]# cat -a test.sh --windows下編譯的檔案,傳遞過來執行的
#!/bin/bash^m$
#this is my first program.^m$
#author:loushen^m$
echo -e "this is my first program,hello world!"^m$
這種windows是dos,而linux則不同,在linux可以直接進行轉換
dos2unix test.sh --dos2unix,這裡的2就是英文中to,均可以這樣理解
然後就可以執行./test.sh檔案了
---------------------
shell 指令碼的執行方式
執行shell指令碼的方式基本上有三種 1 輸入定向到shell指令碼 這種方式是用輸入重定向方式讓shell從給定檔案中讀入命令列並進行相應處理。其一般形式是 bash 指令碼名 例如 bash 2 以指令碼名作為引數 其一般形式是 bash 指令碼名 引數 例如 bash ex2 usr men...
執行Shell指令碼的方式
執行shell指令碼的方式基本上有三種 1 輸入定向到shell指令碼 這種方式是用輸入重定向方式讓shell從給定檔案中讀入命令列並進行相應處理。其一般形式是 bash 指令碼名 例如 bash shell從檔案ex1中讀取命令列,並執行它們。當shell到達檔案末尾時就終止執行,並把控制返回到s...
shell執行命令的方式
想寫這篇文章還得從執行乙個指令碼說起 nohup sh run.sh 看到這樣執行指令碼的方式,剛開始有點不知所措,經過一番理解之後才發現這樣的執行方式考慮的真的很周全 用sh執行指令碼好處是不管指令碼有沒有執行許可權都可以被執行 不管相對路徑.run.sh還是絕對路徑執行 home sas cmn...