經典shell腳本
<<Linux Shell編程>><<Linux系統管理/red hat9從入門到精通>><<24小時精通UNIX shell編程《精通UNIX Shell 腳本編程》 這些都可以買到..到當地書店查詢下吧
② shell腳本具體是干什麼的,是在用什麼的時候會用得到
Shell遵從經典UNIX哲學:把復雜的問題分解成簡單的小問題,然後再把各部分功能組合起來解決復雜問題。
例如我可以用shell腳本來監控伺服器整體的性能,當CPU負載超過我預設的警戒線,磁碟空間的閥值超過我預設的標准,伺服器宕機,這些都可以通過shell編寫腳本做到自動給我發告警郵件或者發簡訊通知我。簡化每日繁瑣的工作步驟,數據的備份,日誌的搜集整理。太多太多了。..
③ 軟體測試常用shell腳本
一 循環
#!/bin/bash
mv perf.log perf.log_bak
while (( "1"=="1" ))
do
java -cp 'conf/:apps/*:lib/*' org.bcos.channel.test.db.PerfomanceOk trans 50000 100 >碰畢譽> perf.log
sleep 550
done
二 預期輸入
#!/bin/bash
set -x
set -e
ethconsole ${node_path}/nodedata-1/data/geth.ipc <<EOF
web3.admin.getPeers(console.log);web3.eth.getBlock(2,console.log)
EOF
/usr/bin/expect << EOF
set timeout 500
spawn ./install_node.sh install
expect "gavin:"
send "Aa12345!\r"
expect "Installing eth environment success"
EOF
三 函數調用
running(){
sleep 1
old_count=`grep +++++ ${host_path}/build/nodedir$1/log/info*|wc -l`
sleep 7
new_count=`grep +++++ ${host_path}/build/nodedir$1/log/info*|wc -l`
if((${old_count}<${new_count}))
then
echo "****** success, node$1 is running normally ******"
#return true
else
echo "****** fail,node$1 is not running ******"
#return false
fi
}
running 3
四 curl命令借口測試
curl -X POST --data '{"jsonrpc":"2.0","method":"admin_nodeInfo","params":[],"id":83}' 127.0.0.1:8545
curl -s -l -H "Content-type: application/json" -X POST -d '{"seqNo":"1067","orgNo":"123","chainId":"100120043","chainName":"he43","chainContent":"test43","extId":"ex43"}' http://10.107.105.143:9000/api/chain/new
五 根據日誌統計
grep '2018-09-06 19:1' appmonitor.log|grep New |awk -F 數散'"' '{a+=$8;b+=1} END {print a,b,a/b}' 統計19:10-19:19分,所有上鏈的次數和平均耗笑段時
④ shell腳本上
| 對於初學者而言,因為沒有實戰經驗,寫不出來 Shell 腳本 很正常,如果工作了幾年的運維老年還是寫不出來,那就是沒主動找需求,缺乏練習,缺乏經驗。針對以上問題,總結了30個生產環境中經典的 Shell 腳本 ,通過這些需求案例,希望能幫助大家提升Shell編寫思路,掌握編寫技巧。 |
先了解下編寫Shell過程中注意事項:
<pre style="margin: 0px; padding: 0px; overflow: auto; white-space: pre-wrap; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">開頭加解釋器:#!/bin/bash
語法縮進,使用四個空格;多加註釋說明。
命名建議規則:變數名大寫、局部變數小寫,函數名小寫,名字體現出實際作用。
默認變數是全局的,在函數中變數local指定為局部變數,避免污染其他作用域。
有兩個 命令 能幫助我調試腳本:set -e 遇到執行非0時退出腳本,set-x 列印執行過程。
寫腳本一定先測試再到生產上。
</pre>
1、獲取隨機字元串或數字
<pre style="margin: 0px; padding: 0px; overflow: auto; white-space: pre-wrap; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">獲取隨機8位字元串:
方法1:
471b94f2
方法2:
vg3BEg==
方法3:
ed9e032c
獲取隨機8位數字:
方法1:
23648321
方法2:
38571131
方法3:
69024815
cksum:列印CRC效驗和統計位元組
</pre>
2、定義一個顏色輸出字元串函數
<pre style="margin: 0px; padding: 0px; overflow: auto; white-space: pre-wrap; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">方法1:
function echo_color() {
if [ 2 33[0m"
elif [ 2 33[0m"
fi
}
方法2:
function echo_color() {
case 2[0m"
;;
red)
echo -e "[31;40m$2[0m"
;;
*)
echo "Example: echo_color red string"
esac
}
使用方法:echo_color green "test"
function關鍵字定義一個函數,可加或不加。
</pre>
3、批量創建用戶
<pre style="margin: 0px; padding: 0px; overflow: auto; white-space: pre-wrap; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">#!/bin/bash
DATE= 1 == "green" ]; then
echo -e "[32;40m 1 == "red" ]; then
echo -e "[31;40m$2[0m"
fi
}
if [ -s USER_FILE {DATE}.bak
echo_color green " {USER_FILE}- USER_FILE
echo "----------------" >> USER &>/dev/null; then
PASS= RANDOM |md5sum |cut -c 1-8)
useradd PASS |passwd --stdin USER USER_FILE
echo " USER User already exists!"
fi
done
</pre>
4、檢查軟體包是否安裝
<pre style="margin: 0px; padding: 0px; overflow: auto; white-space: pre-wrap; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">#!/bin/bash
if rpm -q sysstat &>/dev/null; then
echo "sysstat is already installed."
else
echo "sysstat is not installed!"
fi
</pre>
5、檢查服務狀態
<pre style="margin: 0px; padding: 0px; overflow: auto; white-space: pre-wrap; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">#!/bin/bash
PORT_C= (ps -ef |grep ntpd |grep -vc grep)
if [ PS_C -eq 0 ]; then
echo "內容" | mail -s "主題" [email protected]
fi
</pre>
6、檢查主機存活狀態
<pre style="margin: 0px; padding: 0px; overflow: auto; white-space: pre-wrap; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">方法1:將錯誤IP放到數組裡面判斷是否ping失敗三次
IP_LIST="192.168.18.1 192.168.1.1 192.168.18.2"
for IP in NUM -le 3 ]; do
if ping -c 1 IP Ping is successful."
break
else
# echo " NUM"
FAIL_COUNT[ IP
let NUM++
fi
done
if [ {FAIL_COUNT[1]} Ping is failure!"
unset FAIL_COUNT[*]
fi
done
方法2:將錯誤次數放到FAIL_COUNT變數裡面判斷是否ping失敗三次
IP_LIST="192.168.18.1 192.168.1.1 192.168.18.2"
for IP in IP >/dev/null; then
echo " IP Ping is failure FAIL_COUNT -eq 3 ]; then
echo "$IP Ping is failure!"
fi
done
方法3:利用for循環將ping通就跳出循環繼續,如果不跳出就會走到列印ping失敗
ping_success_status() {
if ping -c 1 IP Ping is successful."
continue
fi
}
IP_LIST="192.168.18.1 192.168.1.1 192.168.18.2"
for IP in IP Ping is failure!"
done
</pre>
7、監控CPU、內存和硬碟利用率
<pre style="margin: 0px; padding: 0px; overflow: auto; white-space: pre-wrap; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">1)CPU
藉助vmstat工具來分析CPU統計信息。
DATE= (ifconfig eth0 |awk -F [ :]+ /inet addr/{print (vmstat |awk NR==3{print (vmstat |awk NR==3{print (vmstat |awk NR==3{print (vmstat |awk NR==3{print (( SY))
if [ DATE
Host: USE
" | mail -s "CPU Monitor" $MAIL
fi
2)內存
DATE= (ifconfig eth0 |awk -F [ :]+ /inet addr/{print (free -m |awk /Mem/{print (free -m |awk /Mem/{print 6- (( USE))
if [ DATE
Host: TOTAL,Use= FREE
" | mail -s "Memory Monitor" $MAIL
fi
3)硬碟
DATE= (ifconfig eth0 |awk -F [ :]+ /inet addr/{print (fdisk -l |awk -F [: ]+ BEGIN{OFS="="}/^Disk /dev/{printf "%s=%sG,", 3} )
PART_USE= 1,int( 6} )
for i in (echo (echo (echo USE -gt 80 ]; then
echo "
Date: IP
Total: PART= MOUNT)
" | mail -s "Disk Monitor" $MAIL
fi
done
</pre>
8、批量主機磁碟利用率監控
<pre style="margin: 0px; padding: 0px; overflow: auto; white-space: pre-wrap; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">前提監控端和被監控端SSH免交互登錄或者密鑰登錄。
寫一個配置文件保存被監控主機SSH連接信息,文件內容格式:IP User Port
HOST_INFO=host.info
for IP in 1} (awk -v ip= 1{print HOST_INFO)
PORT= IP ip== 3} PORT IP df -h > (awk BEGIN{OFS="="}/^/dev/{print 5)} USE_RATE_LIST; do
PART_NAME= {USE_RATE#*=}
if [ PART_NAME Partition usage $USE_RATE%!"
fi
done
done
</pre>
9、檢查網站可用性
<pre style="margin: 0px; padding: 0px; overflow: auto; white-space: pre-wrap; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">1)檢查URL可用性
方法1:
check_url() {
HTTP_CODE= 1)
if [ 1 Access failure!"
fi
}
方法2:
check_url() {
if ! wget -T 10 --tries=1 --spider $1 >/dev/null 2>&1; then
}
使用方法:check_url www..com
2)判斷三次URL可用性
思路與上面檢查主機存活狀態一樣。
方法1:利用循環技巧,如果成功就跳出當前循環,否則執行到最後一行
check_url() {
HTTP_CODE= 1)
if [ URL_LIST; do
check_url URL
check_url URL Access failure!"
done
方法2:錯誤次數保存到變數
URL_LIST=" www..com www.agasgf.com "
for URL in (curl -o /dev/null --connect-timeout 3 -s -w "%{http_code}" HTTP_CODE -ne 200 ]; then
let FAIL_COUNT++
else
break
fi
done
if [ URL Access failure!"
fi
done
方法3:錯誤次數保存到數組
URL_LIST=" www..com www.agasgf.com "
for URL in NUM -le 3 ]; do
HTTP_CODE= URL)
if [ NUM]= NUM下標, {#FAIL_COUNT[ ]} -eq 3 ]; then
echo "Warning: $URL Access failure!"
unset FAIL_COUNT[ ] #清空數組
fi
done
</pre>
10、檢查MySQL主從同步狀態
<pre style="margin: 0px; padding: 0px; overflow: auto; white-space: pre-wrap; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">#!/bin/bash
USER=bak
PASSWD=123456
IO_SQL_STATUS= USER -p 0} ) #gsub去除冒號後面的空格
for i in {i%:*}
THREAD_STATUS= THREAD_STATUS" != "Yes" ]; then
echo "Error: MySQL Master-Slave THREAD_STATUS!"
fi
done
</pre>
動手練一練,讓你的Shell功底上升一個段位!
⑤ java 執行shell語句 shell 執行oracle語句
怎樣在java代碼中調用執行shell腳本
//用法:Runtime.getRuntime.exec("命令");
Stringshpath="/test/test.sh";//程序路徑
Processprocess=null;
Stringmand1=「chmod777」+shpath;
try{
Runtime.getRuntime.exec(mand1).waitFor;
}catch(IOExceptione1){
e1.printStackTrace;
}catch(InterruptedExceptione){
e.printStackTrace;
}
Stringvar="201102";/參數
Stringmand2=「/bin/sh」+shpath+」」+var;
Runtime.getRuntime.exec(mand2).waitFor;
如何在java中執行shell腳本
// 用法:Runtime.getRuntime.exec("命令");
String shpath="/test/test.sh"; //程序路徑
Process process =null;
String mand1 = 「chmod 777 」 + shpath;
try {
Runtime.getRuntime.exec(mand1 ).waitFor;
} catch (IOException e1) {
e1.printStackTrace;
}catch (InterruptedException e) {
e.printStackTrace;
}
String var="201102"; /參數
String mand2 = 「/bin/sh 」 + shpath + 」 」 + var;
Runtime.getRuntime.exec(mand2).waitFor;
java怎麼調用shell腳本
Stringcmdstring="chmoda+xtest.sh";
Processproc=Runtime.getRuntime.exec(cmdstring);
proc.waitFor;//阻塞,直到上述命令執行完
cmdstring="bashtest.sh";//這里也可以是ksh等
proc=Runtime.getRuntime.exec(cmdstring);
//注意下面的操作
stringls_1;
BufferedReaderbufferedReader=newBufferedReader(newInputStreamReader(proc.getInputStream);
while祥配鉛((ls_1=bufferedReader.readLine)!=null);
bufferedReader.close;
proc.waitFor;
為什謹好么要有上面那段操作呢?
原因是:可執行程序的輸出可能會比較多,而運行窗口的輸出緩沖區有限,會造成waitFor一直阻塞。解決的辦法是,利用Java提供的Process類提供的getInputStream,getErrorStream方法讓Java虛擬機截獲被調用程序的標准輸出、錯誤輸出,在waitfor命令之前讀掉輸出緩沖區中的內容。
如何在java中執行shell腳本
在java中執行shell腳本 用賣碧法:Runtime.getRuntime.exec("命令");
String shpath="/test/test.sh"; //程序路徑
Process process =null;
String mand1 = 「chmod 777 」 + shpath;
try {
Runtime.getRuntime.exec(mand1 ).waitFor;
} catch (IOException e1) {
e1.printStackTrace;
}catch (InterruptedException e) {
e.printStackTrace;
}
String var="201102"; /參數
String mand2 = 「/bin/sh 」 + shpath + 」 」 + var;
Runtime.getRuntime.exec(mand2).waitFor;
標簽:作文經典 上一篇:一個人帶頭的成語 一個豬頭帶頭的成語 下一篇:描寫長城的語句 描寫長城美景的語句怎麼通過java去調用並執行shell腳本以及問題總結
以下是我在公司項目中實際應用到的:
/**
*執行系統命令
*@time2016/10/17$17:05$
*/
{
protectedstaticLoggerlogger=LoggerFactory.getLogger(ShareDiskFileUtils.class);
;
;
static{
Stringosname=System.getProperty("os.name").toLowerCase;
isWindow=osname.contains("win");
isLinux=osname.contains("linux");
logger.info("系統環境:"+(isLinux?"Linux":"Window"));
}
/**
*執行命令
*/
(Stringmand)throwsIOException,InterruptedException{
logger.info("執行系統命令:"+mand);
Processprocess=Runtime.getRuntime.exec(getCmdArray(mand));
newStreamPrinter(process.getInputStream,logger).start;
newStreamPrinter(process.getErrorStream,logger).start;
process.waitFor;
returnprocess;
}
/**
*這個非常重要,如果你直接執行mand,會出現一些問題,如果參數中包含一些空格,",'之類的特殊字元,將會執行失敗,
*/
privatestaticString[]getCmdArray(Stringmand){
if(isWindow){
returnnewString[]{"cmd","/c",mand};
}
if(isLinux){
returnnewString[]{"/bin/sh","-c",mand};
}
returnnewString[]{"cmd","/c",mand};
}
}
怎麼通過java去調用並執行shell腳本以及問題總結
// 用法:Runtime.getRuntime.exec("命令");
String shpath="/test/test.sh"; //程序路徑
Process process =null;
String mand1 = 「chmod 777 」 + shpath;
try {
Runtime.getRuntime.exec(mand1 ).waitFor;
} catch (IOException e1) {
e1.printStackTrace;
}catch (InterruptedException e) {
e.printStackTrace;
}
String var="201102"; /參數
String mand2 = 「/bin/sh 」 + shpath + 」 」 + var;
Runtime.getRuntime.exec(mand2).waitFor;
java怎麼執行shell腳本
如果shell腳本和java程序運行在不同的伺服器上,可以使用遠程執行Linux命令執行包,使用ssh2協議連接遠程伺服器,並發送執行命令就行了,ganymed.ssh2相關mave配置如下,你可以自己網路搜索相關資料。
如果shell腳本和java程序在同一台伺服器上,
這里不得不提到java的process類了。
process這個類是一個抽象類,封裝了一個進程(你在調用linux的命令或者shell腳本就是為了執行一個在linux下執行的程序,所以應該使用process類)。
process類提供了執行從進程輸入,執行輸出到進程,等待進程完成,檢查進程的推出狀態,以及shut down掉進程。
.ganymed.ssh2
ganymed-ssh2-build
210
本地執行命令代碼如下:
Stringshpath="/test/test.sh";//程序路徑
Processprocess=null;
Stringmand1=「chmod777」+shpath;
process=Runtime.getRuntime.exec(mand1);
process.waitFor;
如何在java中執行shell腳本
1、最常用的方法:
Processp=Runtime.getRuntime.exec(SHELL_FILE_DIR+RUNNING_SHELL_FILE+
""+param1+""+param2+""+param3);
intrunnngStatus=p.waitFor;
2、通過ProcessBuilder進行調度,這種方法比較直觀,而且參數的設置也比較方便:
ProcessBuilderpb=newProcessBuilder("./"+RUNNING_SHELL_FILE,param1,
param2,param3);
pb.directory(newFile(SHELL_FILE_DIR));
intrunningStatus=0;
Strings=null;
try{
Processp=pb.start;
try{
runningStatus=p.waitFor;
}catch(InterruptedExceptione){
e.printStackTrace;
}
}catch(IOExceptione){
e.printStackTrace;
}
if(runningStatus!=0){
}
return;
參數說明:
RUNNING_SHELL_FILE:要運行的腳本
SHELL_FILE_DIR:要運行的腳本所在的目錄; 當然你也可以把要運行的腳本寫成全路徑。
runningStatus:運行狀態,0標識正常。 詳細可以看java文檔。
param1, param2, param3:可以在RUNNING_SHELL_FILE腳本中直接通過1,1,2,$3分別拿到的參數。
怎麼通過java去調用並執行shell腳本以及問題總結
對於第一個問題:java抓取,並且把結果打包。那麼比較直接的做法就是,java接收各種消息(db,metaq等等),然後藉助於jstorm集群進行調度和抓取。
最後把抓取的結果保存到一個文件中,並且通過調用shell打包, 回傳。 也許有同學會問,
為什麼不直接把java調用odps直接保存文件,答案是,我們的集群不是hz集群,直接上傳odps速度很有問題,因此先打包比較合適。(這里不糾結設計了,我們回到正題)
java調用shell的方法
通過ProcessBuilder進行調度
這種方法比較直觀,而且參數的設置也比較方便, 比如我在實踐中的代碼(我隱藏了部分業務代碼):
ProcessBuilderpb = new ProcessBuilder("./" + RUNNING_SHELL_FILE, param1,
param2, param3);
pb.directory(new File(SHELL_FILE_DIR));
int runningStatus = 0;
String s = null;
try {
Process p = pb.start;
try {
runningStatus = p.waitFor;
} catch (InterruptedException e) {
}
} catch (IOException e) {
}
if (runningStatus != 0) {
}
return;
這里有必要解釋一下幾個參數:
RUNNING_SHELL_FILE:要運行的腳本
SHELL_FILE_DIR:要運行的腳本所在的目錄; 當然你也可以把要運行的腳本寫成全路徑。
runningStatus:運行狀態,0標識正常。 詳細可以看java文檔。
param1, param2, param3:可以在RUNNING_SHELL_FILE腳本中直接通過1,2,$3分別拿到的參數。
直接通過系統Runtime執行shell
這個方法比較暴力,也比較常用, 代碼如下:
p = Runtime.getRuntime.exec(SHELL_FILE_DIR + RUNNING_SHELL_FILE + " "+param1+" "+param2+" "+param3);
p.waitFor;
我們發現,通過Runtime的方式並沒有builder那麼方便,特別是參數方面,必須自己加空格分開,因為exec會把整個字元串作為shell運行。
可能存在的問題以及解決方法
如果你覺得通過上面就能滿足你的需求,那麼可能是要碰壁了。你會遇到以下情況。
沒許可權運行
這個情況我們團隊的朱東方就遇到了, 在做DTS遷移的過程中,要執行包裡面的shell腳本, 解壓出來了之後,發現執行不了。 那麼就按照上面的方法授權吧
java進行一直等待shell返回
這個問題估計更加經常遇到。 原因是, shell腳本中有echo或者print輸出, 導致緩沖區被用完了! 為了避免這種情況, 一定要把緩沖區讀一下, 好處就是,可以對shell的具體運行狀態進行log出來。 比如上面我的例子中我會變成:
ProcessBuilderpb = new ProcessBuilder("./" + RUNNING_SHELL_FILE, keyword.trim,
taskId.toString, fileName);
pb.directory(new File(CASPERJS_FILE_DIR));
int runningStatus = 0;
String s = null;
try {
Process p = pb.start;
BufferedReaderstdInput = new BufferedReader(new InputStreamReader(p.getInputStream));
BufferedReaderstdError = new BufferedReader(new InputStreamReader(p.getErrorStream));
while ((s = stdInput.readLine) != null) {
LOG.error(s);
}
while ((s = stdError.readLine) != null) {
LOG.error(s);
}
try {
runningStatus = p.waitFor;
} catch (InterruptedException e) {
}
記得在start之後, waitFor()之前把緩沖區讀出來打log, 就可以看到你的shell為什麼會沒有按照預期運行。 這個還有一個好處是,可以讀shell裡面輸出的結果, 方便java代碼進一步操作。
也許你還會遇到這個問題,明明手工可以運行的命令,java調用的shell中某一些命令居然不能執行,報錯:命令不存在!
比如我在使用casperjs的時候,手工去執行shell明明是可以執行的,但是java調用的時候,發現總是出錯。
通過讀取緩沖區就能發現錯誤日誌了。 我發現即便自己把安裝的casperjs的bin已經加入了path中(/etc/profile,
各種bashrc中)還不夠。 比如:
exportNODE_HOME="/home/admin/node"
exportCASPERJS_HOME="/home/admin/casperjs"
exportPHANTOMJS_HOME="/home/admin/phantomjs"
exportPATH=$PATH:$JAVA_HOME/bin:/root/bin:$NODE_HOME/bin:$CASPERJS_HOME/bin:$PHANTOMJS_HOME/bin
原來是因為java在調用shell的時候,默認用的是系統的/bin/下的指令。特別是你用root許可權運行的時候。 這時候,你要在/bin下加軟鏈了。針對我上面的例子,就要在/bin下加軟鏈:
ln -s /home/admin/casperjs/bin/casperjscasperjs;
ln -s /home/admin/node/bin/nodenode;
ln -s /home/admin/phantomjs/bin/phantomjsphantomjs;
這樣,問題就可以解決了。
如果是通過java調用shell進行打包,那麼要注意路徑的問題了
因為shell裡面tar的壓縮和解壓可不能直接寫:
tar -zcf /home/admin/data/result.tar.gz /home/admin/data/result
直接給你報錯,因為tar的壓縮源必須到路徑下面, 因此可以寫成
tar -zcf /home/admin/data/result.tar.gz -C /home/admin/data/ result
如果我的shell是在jar包中怎麼辦?
答案是:解壓出來。再按照上面指示進行操作。(1)找到路徑
String jarPath = findClassJarPath(ClassLoaderUtil.class);
JarFiletopLevelJarFile = null;
try {
topLevelJarFile = new JarFile(jarPath);
Enumeration entries = topLevelJarFile.entries;
while (entries.hasMoreElements) {
JarEntryentry = entries.nextElement;
if (!entry.isDirectory entry.getName.endsWith(".sh")) {
對你的shell文件進行處理
}
}
對文件處理的方法就簡單了,直接touch一個臨時文件,然後把數據流寫入,代碼:
FileUtils.touch(tempjline);
tempjline.deleteOnExit;
FileOutputStreamfos = new FileOutputStream(tempjline);
IOUtils.(ClassLoaderUtil.class.getResourceAsStream(r), fos);
fos.close;
如何在java中執行shell腳本
首先你可以網路搜一下 java Process 類的用法,很多博文都有講解。
另外我補充一下我再使用過程中的一些點:
process = Runtime.getRuntime.exec(new String[]{"/bin/sh","-c",shellContext});
其中 shellContext 是shel腳本字元串
這句提交的時候,不少博文 exec中是直接提交shellContext。
但是對於一些場景不適用,取出來數據跟直接運行shell腳本有差異,可以改成我這種寫法。
標簽:作文經典 上一篇:一個人帶頭的成語 一個豬頭帶頭的成語 下一篇:描寫長城的語句 描寫長城美景的語句⑥ linux下 如何用c++來操作shell腳本
比如生成一個文件夾tmp(c++)
string cmd = string("mkdir -p") + string("tmp"); //string cmd = string("mkdir -p tmp");
system(cmd.c_str());
上面只是給個範例,具體要執行什麼命令,替換一下,然後類似操作即可.
記得別忘記頭文件,
// system() 頭文件: <process.h> 或<stdlib.h>
// _wsystem() 頭文件:<process.h> 或<stdlib.h> 或<wchar.h>
在C++下面么最好加前綴c
#include <cstdlib> //system
#include <cstring> //string
⑦ 分享70個經典的 Shell 腳本面試題與答案
1) 如何向腳本傳遞參數 ?
./script argument
2) 如何在腳本中使用參數 ?
第一個參數 : $1 ,第二個參數 : $2
cp $1 $2
3) 如何計算傳遞進來的參數 ?
$#
4) 如何在腳本中獲取腳本名稱 ?
$0
5) 如何檢查之前的命令是否運行成功 ?
$?
6) 如何獲取文件的最後一行 ?
tail-1
7) 如何獲取文件的第一行 ?
head-1
8) 如何獲取一個文件每一行的第三個元素 ?
awk'{print $3}'
9) 假如文件中每行第一個元素是 FIND,如何獲取第二個元素
awk'{ if ($1 == "FIND") print $2}'
10) 如何調試 bash 腳本
將 -xv 參數加到 #!/bin/bash 後
例子:
#!/bin/bash –xv
11) 舉例如何寫一個函數 ?
12) 如何向連接兩個字元串 ?
輸出
HelloWorld
13) 如何進行兩個整數相加 ?
14) 如何檢查文件系統中是否存在某個文件 ?
15) 寫出 shell 腳本中所有循環語法 ?
for 循環 :
while 循環 :
until 循環 :
16) 每個腳本開始的 #!/bin/sh 或 #!/bin/bash 表示什麼意思 ?
這一行說明要使用的 shell 。 #!/bin/bash 表示腳本使用 /bin/bash 。對於 python 腳本,就是 #!/usr/bin/python 。
17) 如何獲取文本文件的第 10 行 ?
head -10 file|tail -1
18) bash 腳本文件的第一個符號是什麼
#
19) 命令: [ -z "" ] && echo 0 || echo 1 的輸出是什麼
0
20) 命令 「export」 有什麼用 ?
使變數在子 shell 中可用。
21) 如何在後台運行腳本 ?
nohup command&
大部分時間我們可能是遠程使用Linux,我碰到過由於網路斷線使得在後台運行的 command & 沒了...
22) "chmod 500 script" 做什麼 ?
使腳本所有者擁有可執行許可權。
23) ">" 做什麼 ?
重定向輸出流到文件或另一個流。
24) & 和 && 有什麼區別
25) 什麼時候要在 [ condition ] 之前使用 「if」 ?
當條件滿足時需要運行多條命令的時候。
26) 命令: name=John && echo "My name is $name" 的輸出是什麼
My name is John
27) bash shell 腳本中哪個符號用於注釋 ?
#
28) 命令: echo ${new:-variable} 的輸出是什麼
variable
29) ' 和 " 引號有什麼區別 ?
30) 如何在腳本文件中重定向標准輸出和標准錯誤流到 log.txt 文件 ?
在腳本文件中添加 "exec >log.txt 2>&1" 命令。
31) 如何只用 echo 命令獲取字元串變數的一部分 ?
例子:
32) 如果給定字元串 variable="User:123:321:/home/dir" ,如何只用 echo 命令獲取 home_dir ?
echo ${variable#*:*:*:}
或
echo ${variable##*:}
33) 如何從上面的字元串中獲取 「User」 ?
echo ${variable%:*:*:*}
或
echo ${variable%%:*}
34) 如何使用 awk 列出 UID 小於 100 的用戶 ?
awk -F: '$3<100' /etc/passwd
35) 寫程序為用戶計算主組數目並顯示次數和組名
36) 如何在 bash shell 中更改標準的域分隔符為 ":" ?
IFS=":"
37) 如何獲取變數長度 ?
${#variable}
38) 如何列印變數的最後 5 個字元 ?
echo ${variable: -5}
39) ${variable:-10} 和 ${variable: -10} 有什麼區別?
40) 如何只用 echo 命令替換字元串的一部分 ?
echo ${variable//pattern/replacement}
41) 哪個命令將命令替換為大寫 ?
tr '[:lower:]' '[:upper:]'
42) 如何計算本地用戶數目 ?
wc -l /etc/passwd|cut -d" " -f1 或者 cat /etc/passwd|wc -l
43) 不用 wc 命令如何計算字元串中的單詞數目 ?
44) "export $variable" 或 "export variable" 哪個正確 ?
export variable
45) 如何列出第二個字母是 a 或 b 的文件 ?
ls -d ?[ab]*
46) 如何將整數 a 加到 b 並賦值給 c ?
47) 如何去除字元串中的所有空格 ?
echo $string|tr -d " "
48) 重寫這個命令,將輸出變數轉換為復數: item="car"; echo "I like $item" ?
item="car"; echo "I like ${item}s"
49) 寫出輸出數字 0 到 100 中 3 的倍數(0 3 6 9 …)的命令 ?
for i in {0..100..3}; do echo $i; done
或
for (( i=0; i<=100; i=i+3 )); do echo "Welcome $i times"; done
50) 如何列印傳遞給腳本的所有參數 ?
echo $*
或
echo $@
51) [ $a == $b ] 和 [ $a -eq $b ] 有什麼區別
52) = 和 == 有什麼區別
53) 寫出測試 $a 是否大於 12 的命令 ?
[ $a -gt 12 ]
54) 寫出測試 $b 是否小於等於 12 的命令 ?
[ $b -le 12 ]
55) 如何檢查字元串是否以字母 "abc" 開頭 ?
[[ $string == abc* ]]
56) [[ $string == abc* ]] 和 [[ $string == "abc*" ]] 有什麼區別
57) 如何列出以 ab 或 xy 開頭的用戶名 ?
egrep "^ab|^xy" /etc/passwd|cut -d: -f1
58) bash 中 $! 表示什麼意思 ?
後台最近執行命令的 PID.
59) $? 表示什麼意思 ?
前台最近命令的結束狀態。
60) 如何輸出當前 shell 的 PID ?
echo $$
61) 如何獲取傳遞給腳本的參數數目 ?
echo $#
62) $* 和 $@ 有什麼區別
63) 如何在 bash 中定義數組 ?
array=("Hi" "my" "name" "is")
64) 如何列印數組的第一個元素 ?
echo ${array[0]}
65) 如何列印數組的所有元素 ?
echo ${array[@]}
66) 如何輸出所有數組索引 ?
echo ${!array[@]}
67) 如何移除數組中索引為 2 的元素 ?
unset array[2]
68) 如何在數組中添加 id 為 333 的元素 ?
array[333]="New_element"
69) shell 腳本如何獲取輸入的值 ?
a) 通過參數
./script param1 param2
b) 通過 read 命令
read -p "Destination backup Server : " desthost
70) 在腳本中如何使用 "expect" ?
⑧ Linux使用之grep,shell腳本(一)
在使用Linux的過程中,場景有時候便會涉及到查找文本文件的內容,假如現在我們想要在一個三百多行的文本中找到特定的語句,或者在這其中查找是否含有特定的欄位應該怎麼辦呢?
這里便出現了專門的文本處理工具——grep,grep是Linux中常用的文本處理工具之一。
grep的全稱為「 Global search Regular Expression and Print out the line」。
全稱中的「Glibal search」意思為全局搜索的意思。
全稱中的「Regular Expression」意思為正則表達式。
所以從全稱中就可以理解為gerp是一個可以利用正則表達式的全型激局搜索工具。grep會按照正則表達式的匹配原則在文本文件中按照逐行匹配處理的方法來處理文本並輸出。
來看看grep的用法。
來看看案例。
案例1.統計出/etc/passwd文件中其默認shell為非/sbin/nologin的用戶個數,並將用戶都顯示出來
上面的案例開始匹配了/sbin/nologin關鍵詞,但是案例中只需要除了它之外的shell,所以講它使用-v選項排除開就可以了。
案例2.查出用戶UID最大值的用戶卜森襪名、UID及shell類型
案例3.統計當前連接本機的每個遠程主機IP的連接數,並按從大到小排序
上面的案例中ss -nt 查看連接情況,然春頌後將EATAB狀態的過濾出來,在進行處理,最後提取出結果並完成排序。
案例4:編寫腳本disk.sh,顯示當前硬碟分區中空間利用率最大的值
案例5.編寫腳本 systeminfo.sh,顯示當前主機系統信息,包括:主機名,IPv4地址,操作系統版本,內核版本,CPU型號,內存大小,硬碟大小
⑨ 如何編寫一個shell腳本
如何編寫一個shell腳本
本文結合大量實例闡述如何編寫一個shell腳本。
為什麼要進行shell編程
在Linux系統中,雖然有各種各樣的圖形化介面工具,但是sell仍然是一個非常靈活的工具。Shell不僅僅是命令的收集,而且是一門非常棒的編程語言。您可以通過使用shell使大量的任務自動化,shell特別擅長系統管理任務,尤其適合那些易用性、可維護性和便攜性比效率更重要的任務。
下面,讓我們一起來看看shell是如何工作的:
建立一個腳本
Linux中有好多中不同的shell,但是通常我們使用bash (bourne again shell) 進行shell編程,因為bash是免費的並且很容易使用。所以在本文中筆者所提供的腳本都是使用bash(但是在大多數情況下,這些腳本同樣可以在bash的大姐,bourne shell中運行)。
如同其他語言一樣,通過我們使用任意一種文字編輯器,比如nedit、kedit、emacs、vi
等來編寫我們的shell程序。
程序必須以下面的行開始(必須方在文件的第一行):
#!/bin/sh
符號#!用來告訴系統它後面的參數是用來執行該文件的程序。在這個例子中我們使用/bin/sh來執行程序。
當編輯好腳本時,如果要執行該腳本,還必須使其可執行。
要使腳本可執行:
chmod +x filename
然後,您可以通過輸入: ./filename 來執行您的腳本。
注釋
在進行shell編程時,以#開頭的句子表示注釋,直到這一行的結束。我們真誠地建議您在程序中使用注釋。如果您使用了注釋,那麼即使相當長的時間內沒有使用該腳本,您也能在很短的時間內明白該腳本的作用及工作原理。
變數
在其他編程語言中您必須使用變數。在shell編程中,所有的變數都由字元串組成,並且您不需要對變數進行聲明。要賦值給一個變數,您可以這樣寫:
變數名=值
取出變數值可以加一個美元符號($)在變數前面:
#!/bin/sh
#對變數賦值:
a="hello world"
# 現在列印變數a的內容:
echo "A is:"
echo $a
在您的編輯器中輸入以上內容,然後將其保存為一個文件first。之後執行chmod +x first
使其可執行,最後輸入./first執行該腳本。
這個腳本將會輸出:
A is:
hello world
有時候變數名很容易與其他文字混淆,比如:
num=2
echo "this is the $numnd"
這並不會列印出"this is the 2nd",而僅僅列印"this is the ",因為shell會去搜索變數numnd的值,但是這個變數時沒有值的。可以使用花括弧來告訴shell我們要列印的是num變數:
num=2
echo "this is the ${num}nd"
這將列印: this is the 2nd
有許多變數是系統自動設定的,這將在後面使用這些變數時進行討論。
如果您需要處理數學表達式,那麼您需要使用諸如expr等程序(見下面)。
除了一般的僅在程序內有效的shell變數以外,還有環境變數。由export關鍵字處理過的變數叫做環境變數。我們不對環境變數進行討論,因為通常情況下僅僅在登錄腳本中使用環境變數。
Shell命令和流程式控制制
在shell腳本中可以使用三類命令:
1)Unix 命令:
雖然在shell腳本中可以使用任意的unix命令,但是還是由一些相對更常用的命令。這些命令通常是用來進行文件和文字操作的。
常用命令語法及功能
echo "some text": 將文字內容列印在屏幕上
ls: 文件列表
wc –l filewc -w filewc -c file: 計算文件行數計算文件中的單詞數計算文件中的字元數
cp sourcefile destfile: 文件拷貝
mv oldname newname : 重命名文件或移動文件
rm file: 刪除文件
grep 'pattern' file: 在文件內搜索字元串比如:grep 'searchstring' file.txt
cut -b colnum file: 指定欲顯示的文件內容範圍,並將它們輸出到標准輸出設備比如:輸出每行第5個到第9個字元cut -b5-9 file.txt千萬不要和cat命令混淆,這是兩個完全不同的命令
cat file.txt: 輸出文件內容到標准輸出設備(屏幕)上
file somefile: 得到文件類型
read var: 提示用戶輸入,並將輸入賦值給變數
sort file.txt: 對file.txt文件中的行進行排序
uniq: 刪除文本文件中出現的行列比如: sort file.txt | uniq
expr: 進行數學運算Example: add 2 and 3expr 2 "+" 3
find: 搜索文件比如:根據文件名搜索find . -name filename -print
tee: 將數據輸出到標准輸出設備(屏幕) 和文件比如:somecommand | tee outfile
basename file: 返回不包含路徑的文件名比如: basename /bin/tux將返回 tux
dirname file: 返迴文件所在路徑比如:dirname /bin/tux將返回 /bin
head file: 列印文本文件開頭幾行
tail file : 列印文本文件末尾幾行
sed: Sed是一個基本的查找替換程序。可以從標准輸入(比如命令管道)讀入文本,並將結果輸出到標准輸出(屏幕)。該命令採用正則表達式(見參考)進行搜索。不要和shell中的通配符相混淆。比如:將linuxfocus 替換為 LinuxFocus :cat text.file | sed 's/linuxfocus/LinuxFocus/' > newtext.file
awk: awk 用來從文本文件中提取欄位。預設地,欄位分割符是空格,可以使用-F指定其他分割符。cat file.txt | awk -F, '{print $1 "," $3 }'這里我們使用,作為欄位分割符,同時列印第一個和第三個欄位。如果該文件內容如下: Adam Bor, 34, IndiaKerry Miller, 22, USA命令輸出結果為:Adam Bor, IndiaKerry Miller, USA
2) 概念: 管道, 重定向和 backtick
這些不是系統命令,但是他們真的很重要。
管道 (|) 將一個命令的輸出作為另外一個命令的輸入。
grep "hello" file.txt | wc -l
在file.txt中搜索包含有」hello」的行並計算其行數。
在這里grep命令的輸出作為wc命令的輸入。當然您可以使用多個命令。
重定向:將命令的結果輸出到文件,而不是標准輸出(屏幕)。
> 寫入文件並覆蓋舊文件
>> 加到文件的尾部,保留舊文件內容。
反短斜線
使用反短斜線可以將一個命令的輸出作為另外一個命令的一個命令行參數。
命令:
find . -mtime -1 -type f -print
用來查找過去24小時(-mtime –2則表示過去48小時)內修改過的文件。如果您想將所有查找到的文件打一個包,則可以使用以下腳本:
#!/bin/sh
# The ticks are backticks (`) not normal quotes ('):
tar -zcvf lastmod.tar.gz `find . -mtime -1 -type f -print`
3) 流程式控制制
"if" 表達式 如果條件為真則執行then後面的部分:
if ....; then
....
elif ....; then
....
else
....
fi
大多數情況下,可以使用測試命令來對條件進行測試。比如可以比較字元串、判斷文件是否存在及是否可讀等等…
通常用" [ ] "來表示條件測試。注意這里的空格很重要。要確保方括弧的空格。
[ -f "somefile" ] :判斷是否是一個文件
[ -x "/bin/ls" ] :判斷/bin/ls是否存在並有可執行許可權
[ -n "$var" ] :判斷$var變數是否有值
[ "$a" = "$b" ] :判斷$a和$b是否相等
執行man test可以查看所有測試表達式可以比較和判斷的類型。
直接執行以下腳本:
#!/bin/sh
if [ "$SHELL" = "/bin/bash" ]; then
echo "your login shell is the bash (bourne again shell)"
else
echo "your login shell is not bash but $SHELL"
fi
變數$SHELL包含了登錄shell的名稱,我們和/bin/bash進行了比較。
快捷操作符
熟悉C語言的朋友可能會很喜歡下面的表達式:
[ -f "/etc/shadow" ] && echo "This computer uses shadow passwors"
這里 && 就是一個快捷操作符,如果左邊的表達式為真則執行右邊的語句。您也可以認為是邏輯運算中的與操作。上例中表示如果/etc/shadow文件存在則列印」 This computer uses shadow passwors」。同樣或操作(||)在shell編程中也是可用的。這里有個例子:
#!/bin/sh
mailfolder=/var/spool/mail/james
[ -r "$mailfolder" ]' '{ echo "Can not read $mailfolder" ; exit 1; }
echo "$mailfolder has mail from:"
grep "^From " $mailfolder
該腳本首先判斷mailfolder是否可讀。如果可讀則列印該文件中的"From" 一行。如果不可讀則或操作生效,列印錯誤信息後腳本退出。這里有個問題,那就是我們必須有兩個命令:
-列印錯誤信息
-退出程序
我們使用花括弧以匿名函數的形式將兩個命令放到一起作為一個命令使用。一般函數將在下文提及。
不用與和或操作符,我們也可以用if表達式作任何事情,但是使用與或操作符會更便利很多。
case表達式可以用來匹配一個給定的字元串,而不是數字。
case ... in
...) do something here ;;
esac
讓我們看一個例子。 file命令可以辨別出一個給定文件的文件類型,比如:
file lf.gz
這將返回:
lf.gz: gzip compressed data, deflated, original filename,
last modified: Mon Aug 27 23:09:18 2001, os: Unix
我們利用這一點寫了一個叫做smartzip的腳本,該腳本可以自動解壓bzip2, gzip 和zip 類型的壓縮文件:
#!/bin/sh
ftype=`file "$1"`
case "$ftype" in
"$1: Zip archive"*)
unzip "$1" ;;
"$1: gzip compressed"*)
gunzip "$1" ;;
"$1: bzip2 compressed"*)
bunzip2 "$1" ;;
*) error "File $1 can not be uncompressed with smartzip";;
esac
您可能注意到我們在這里使用了一個特殊的變數$1。該變數包含了傳遞給該程序的第一個參數值。也就是說,當我們運行:
smartzip articles.zip
$1 就是字元串 articles.zip
select 表達式是一種bash的擴展應用,尤其擅長於互動式使用。用戶可以從一組不同的值中進行選擇。
select var in ... ; do
break
done
.... now $var can be used ....
下面是一個例子:
#!/bin/sh
echo "What is your favourite OS?"
select var in "Linux" "Gnu Hurd" "Free BSD" "Other"; do
break
done
echo "You have selected $var"
下面是該腳本運行的結果:
What is your favourite OS?
1) Linux
2) Gnu Hurd
3) Free BSD
4) Other
#? 1
You have selected Linux
您也可以在shell中使用如下的loop表達式:
while ...; do
....
done
while-loop 將運行直到表達式測試為真。will run while the expression that we test for is true. 關鍵字"break" 用來跳出循環。而關鍵字」continue」用來不執行餘下的部分而直接跳到下一個循環。
for-loop表達式查看一個字元串列表 (字元串用空格分隔) 然後將其賦給一個變數:
for var in ....; do
....
done
在下面的例子中,將分別列印ABC到屏幕上:
#!/bin/sh
for var in A B C ; do
echo "var is $var"
done
下面是一個更為有用的腳本showrpm,其功能是列印一些RPM包的統計信息:
#!/bin/sh
# list a content summary of a number of RPM packages
# USAGE: showrpm rpmfile1 rpmfile2 ...
# EXAMPLE: showrpm /cdrom/RedHat/RPMS/*.rpm
for rpmpackage in $*; do
if [ -r "$rpmpackage" ];then
echo "=============== $rpmpackage =============="
rpm -qi -p $rpmpackage
else
echo "ERROR: cannot read file $rpmpackage"
fi
done
這里出現了第二個特殊的變數$*,該變數包含了所有輸入的命令行參數值。如果您運行showrpm openssh.rpm w3m.rpm webgrep.rpm
此時 $* 包含了 3 個字元串,即openssh.rpm, w3m.rpm and webgrep.rpm.
引號
在向程序傳遞任何參數之前,程序會擴展通配符和變數。這里所謂擴展的意思是程序會把通配符(比如*)替換成合適的文件名,它變數替換成變數值。為了防止程序作這種替換,您可以使用引號:讓我們來看一個例子,假設在當前目錄下有一些文件,兩個jpg文件, mail.jpg 和tux.jpg。
#!/bin/sh
echo *.jpg
這將列印出"mail.jpg tux.jpg"的結果。
引號 (單引號和雙引號) 將防止這種通配符擴展:
#!/bin/sh
echo "*.jpg"
echo '*.jpg'
這將列印"*.jpg" 兩次。
單引號更嚴格一些。它可以防止任何變數擴展。雙引號可以防止通配符擴展但允許變數擴展。
#!/bin/sh
echo $SHELL
echo "$SHELL"
echo '$SHELL'
運行結果為:
/bin/bash
/bin/bash
$SHELL
最後,還有一種防止這種擴展的方法,那就是使用轉義字元——反斜桿:
echo *.jpg
echo $SHELL
這將輸出:
*.jpg
$SHELL
Here documents
當要將幾行文字傳遞給一個命令時,here documents(譯者註:目前還沒有見到過對該詞適合的翻譯)一種不錯的方法。對每個腳本寫一段幫助性的文字是很有用的,此時如果我們四有那個here documents就不必用echo函數一行行輸出。 一個 "Here document" 以 << 開頭,後面接上一個字元串,這個字元串還必須出現在here document的末尾。下面是一個例子,在該例子中,我們對多個文件進行重命名,並且使用here documents列印幫助:
#!/bin/sh
# we have less than 3 arguments. Print the help text:
if [ $# -lt 3 ] ; then
cat <<HELP
ren -- renames a number of files using sed regular expressions
USAGE: ren 'regexp' 'replacement' files...
EXAMPLE: rename all *.HTM files in *.html:
ren 'HTM$' 'html' *.HTM
HELP
exit 0
fi
OLD="$1"
NEW="$2"
# The shift command removes one argument from the list of
# command line arguments.
shift
shift
# $* contains now all the files:
for file in $*; do
if [ -f "$file" ] ; then
newfile=`echo "$file" | sed "s/${OLD}/${NEW}/g"`
if [ -f "$newfile" ]; then
echo "ERROR: $newfile exists already"
else
echo "renaming $file to $newfile ..."
mv "$file" "$newfile"
fi
fi
done
這是一個復雜一些的例子。讓我們詳細討論一下。第一個if表達式判斷輸入命令行參數是否小於3個 (特殊變數$# 表示包含參數的個數) 。如果輸入參數小於3個,則將幫助文字傳遞給cat命令,然後由cat命令將其列印在屏幕上。列印幫助文字後程序退出。 如果輸入參數等於或大於3個,我們就將第一個參數賦值給變數OLD,第二個參數賦值給變數NEW。下一步,我們使用shift命令將第一個和第二個參數從參數列表中刪除,這樣原來的第三個參數就成為參數列表$*的第一個參數。然後我們開始循環,命令行參數列表被一個接一個地被賦值給變數$file。接著我們判斷該文件是否存在,如果存在則通過sed命令搜索和替換來產生新的文件名。然後將反短斜線內命令結果賦值給newfile。這樣我們就達到了我們的目的:得到了舊文件名和新文件名。然後使用mv命令進行重命名。
函數
如果您寫了一些稍微復雜一些的程序,您就會發現在程序中可能在幾個地方使用了相同的代碼,並且您也會發現,如果我們使用了函數,會方便很多。一個函數是這個樣子的:
functionname()
{
# inside the body $1 is the first argument given to the function
# $2 the second ...
body
}
您需要在每個程序的開始對函數進行聲明。
下面是一個叫做xtitlebar的腳本,使用這個腳本您可以改變終端窗口的名稱。這里使用了一個叫做help的函數。正如您可以看到的那樣,這個定義的函數被使用了兩次。
#!/bin/sh
# vim: set sw=4 ts=4 et:
help()
{
cat <<HELP
xtitlebar -- change the name of an xterm, gnome-terminal or kde konsole
USAGE: xtitlebar [-h] "string_for_titelbar"
OPTIONS: -h help text
EXAMPLE: xtitlebar "cvs"
HELP
exit 0
}
# in case of error or if -h is given we call the function help:
[ -z "$1" ] && help
[ "$1" = "-h" ] && help
# send the escape sequence to change the xterm titelbar:
echo -e "33]0;$107"
#
在腳本中提供幫助是一種很好的編程習慣,這樣方便其他用戶(和您)使用和理解腳本。
命令行參數
我們已經見過$* 和 $1, $2 ... $9 等特殊變數,這些特殊變數包含了用戶從命令行輸入的參數。迄今為止,我們僅僅了解了一些簡單的命令行語法(比如一些強制性的參數和查看幫助的-h選項)。但是在編寫更復雜的程序時,您可能會發現您需要更多的自定義的選項。通常的慣例是在所有可選的參數之前加一個減號,後面再加上參數值 (比如文件名)。
有好多方法可以實現對輸入參數的分析,但是下面的使用case表達式的例子無遺是一個不錯的方法。
#!/bin/sh
help()
{
cat <<HELP
This is a generic command line parser demo.
USAGE EXAMPLE: cmdparser -l hello -f -- -somefile1 somefile2
HELP
exit 0
}
while [ -n "$1" ]; do
case $1 in
-h) help;shift 1;; # function help is called
-f) opt_f=1;shift 1;; # variable opt_f is set
-l) opt_l=$2;shift 2;; # -l takes an argument -> shift by 2
--) shift;break;; # end of options
-*) echo "error: no such option $1. -h for help";exit 1;;
*) break;;
esac
done
echo "opt_f is $opt_f"
echo "opt_l is $opt_l"
echo "first arg is $1"
echo "2nd arg is $2"
您可以這樣運行該腳本:
cmdparser -l hello -f -- -somefile1 somefile2
返回的結果是:
opt_f is 1
opt_l is hello
first arg is -somefile1
2nd arg is somefile2
這個腳本是如何工作的呢?腳本首先在所有輸入命令行參數中進行循環,將輸入參數與case表達式進行比較,如果匹配則設置一個變數並且移除該參數。根據unix系統的慣例,首先輸入的應該是包含減號的參數。
實例
一般編程步驟
現在我們來討論編寫一個腳本的一般步驟。任何優秀的腳本都應該具有幫助和輸入參數。並且寫一個偽腳本(framework.sh),該腳本包含了大多數腳本都需要的框架結構,是一個非常不錯的主意。這時候,在寫一個新的腳本時我們只需要執行一下命令:
cp framework.sh myscript
然後再插入自己的函數。
讓我們再看兩個例子:
二進制到十進制的轉換
腳本 b2d 將二進制數 (比如 1101) 轉換為相應的十進制數。這也是一個用expr命令進行數學運算的例子:
#!/bin/sh
# vim: set sw=4 ts=4 et:
help()
{
cat <<HELP
b2h -- convert binary to decimal
USAGE: b2h [-h] binarynum
OPTIONS: -h help text
EXAMPLE: b2h 111010
will return 58
HELP
exit 0
}
error()
{
# print an error and exit
echo "$1"
exit 1
}
lastchar()
{
# return the last character of a string in $rval
if [ -z "$1" ]; then
# empty string
rval=""
return
fi
# wc puts some space behind the output this is why we need sed:
numofchar=`echo -n "$1" | wc -c | sed 's/ //g' `
# now cut out the last char
rval=`echo -n "$1" | cut -b $numofchar`
}
chop()
{
# remove the last character in string and return it in $rval
if [ -z "$1" ]; then
# empty string
rval=""
return
fi
# wc puts some space behind the output this is why we need sed:
numofchar=`echo -n "$1" | wc -c | sed 's/ //g' `
if [ "$numofchar" = "1" ]; then
# only one char in string
rval=""
return
fi
numofcharminus1=`expr $numofchar "-" 1`
# now cut all but the last char:
rval=`echo -n "$1" | cut -b 0-${numofcharminus1}`
}
while [ -n "$1" ]; do
case $1 in
-h) help;shift 1;; # function help is called
--) shift;break;; # end of options
-*) error "error: no such option $1. -h for help";;
*) break;;
esac
done
# The main program
sum=0
weight=1
# one arg must be given:
[ -z "$1" ] && help
binnum="$1"
binnumorig="$1"
while [ -n "$binnum" ]; do
lastchar "$binnum"
if [ "$rval" = "1" ]; then
sum=`expr "$weight" "+" "$sum"`
fi
# remove the last position in $binnum
chop "$binnum"
binnum="$rval"
weight=`expr "$weight" "*" 2`
done
echo "binary $binnumorig is decimal $sum"
#
該腳本使用的演算法是利用十進制和二進制數權值 (1,2,4,8,16,..),比如二進制"10"可以這樣轉換成十進制:
0 * 1 + 1 * 2 = 2
為了得到單個的二進制數我們是用了lastchar 函數。該函數使用wc –c計算字元個數,然後使用cut命令取出末尾一個字元。Chop函數的功能則是移除最後一個字元。
文件循環程序
或許您是想將所有發出的郵件保存到一個文件中的人們中的一員,但是在過了幾個月以後,這個文件可能會變得很大以至於使對該文件的訪問速度變慢。下面的腳本rotatefile 可以解決這個問題。這個腳本可以重命名郵件保存文件(假設為outmail)為outmail.1,而對於outmail.1就變成了outmail.2 等等等等...
#!/bin/sh
# vim: set sw=4 ts=4 et:
ver="0.1"
help()
{
cat <<HELP
rotatefile -- rotate the file name
USAGE: rotatefile [-h] filename
OPTIONS: -h help text
EXAMPLE: rotatefile out
This will e.g rename out.2 to out.3, out.1 to out.2, out to out.1
and create an empty out-file
The max number is 10
version $ver
HELP
exit 0
}
error()
{
echo "$1"
exit 1
}
while [ -n "$1" ]; do
case $1 in
-h) help;shift 1;;
--) break;;
-*) echo "error: no such option $1. -h for help";exit 1;;
*) break;;
esac
done
# input check:
if [ -z "$1" ] ; then
error "ERROR: you must specify a file, use -h for help"
fi
filen="$1"
# rename any .1 , .2 etc file:
for n in 9 8 7 6 5 4 3 2 1; do
if [ -f "$filen.$n" ]; then
p=`expr $n + 1`
echo "mv $filen.$n $filen.$p"
mv $filen.$n $filen.$p
fi
done
# rename the original file:
if [ -f "$filen" ]; then
echo "mv $filen $filen.1"
mv $filen $filen.1
fi
echo touch $filen
touch $filen
這個腳本是如何工作的呢?在檢測用戶提供了一個文件名以後,我們進行一個9到1的循環。文件9被命名為10,文件8重命名為9等等。循環完成之後,我們將原始文件命名為文件1同時建立一個與原始文件同名的空文件。
調試
最簡單的調試命令當然是使用echo命令。您可以使用echo在任何懷疑出錯的地方列印任何變數值。這也是絕大多數的shell程序員要花費80%的時間來調試程序的原因。Shell程序的好處在於不需要重新編譯,插入一個echo命令也不需要多少時間。
shell也有一個真實的調試模式。如果在腳本"strangescript" 中有錯誤,您可以這樣來進行調試:
sh -x strangescript
這將執行該腳本並顯示所有變數的值。
shell還有一個不需要執行腳本只是檢查語法的模式。可以這樣使用:
sh -n your_script
這將返回所有語法錯誤。
⑩ shell腳本中的腳本語句起什麼作用
起 聲明 或者 執行某操作的作用
比方 經典的hello world的shell版本
#!/bin/bash
echo "hello world"
其中 第一行激廳為執行解釋器返閉環明世隱境
第二行則是往標准輸出輸出hello world