最近利用業余時間學習了shell 並做了個例子
實現的功能是 : 監聽demo文件夾下的文件,只要新增了 .js的文件就把對應的文件名重組,拼接, 最后寫入到demo.js里面.
文件結構如下 :
demo.sh代碼如下
while : ;
do
if [ -f oldfiles.log ]
then
#按照時間排序 並取第一行 就是最新建的文件
newfile=` ls -t | head -1 `
#查找到最新建的文件 如果不存在 就拋出錯誤到dev/null(無底洞)
cat oldfiles.log | grep $newfile >/dev/null
#如果上一條命令執行后的結束代碼不是0則執行下面的命令
if [ $? -eq 1 ]
then
echo "there is a new file: $newfile"
# 先把.js結尾的文件獲取到 就是只監控js文件
if [ "${newfile##*.}"x = "js"x ]
then
#再判斷是 class 開頭的還是 route 開頭的
newfilehead=`echo $newfile | cut -d . -f 1`
val_class='class'
val_route='route'
#如果是route開頭的文件
#ecui.esr.loadRoute(‘smile.monkey’);
if [ "$newfilehead"x = "route"x ]
then
# echo $newfile
noHeadStr=`echo ${newfile#*.}`
noTailStr=`echo ${noHeadStr%.*}`
# echo "ecui.esr.loadRoute(‘"${noTailStr}"’);" >>demo.js
echo "ecui.esr.loadRoute('"${noTailStr}"');" >>demo.js
fi
#如果是class開頭的文件
#ecui.esr.loadClass(‘smile.monkey’);
if [ "$newfilehead"x = "class"x ]
then
# echo $newfile
noHeadStr=`echo ${newfile#*.}`
# echo $noHeadStr
noTailStr=`echo ${noHeadStr%.*}`
echo $noTailStr
cat demo.js >oldfiles.log
echo "ecui.esr.loadClass('"${noTailStr}"');" >demo.js
cat oldfiles.log | while read line
do
echo $line>>demo.js
done
rm oldfiles.log
fi
fi
echo $newfile >> oldfiles.log
else
echo "there is no new files"
fi
else
ls -t -r > oldfiles.log
echo "cache old files info"
fi
sleep 1; done;
執行demo.sh之后 會無限循環執行 達到遍歷的目的.
最后總結:合理使用shell 能幫助我們自動化完成好多任務 ,提高工作效率
如果沒有shell基礎的同學先看看一下鏈接 稍微學習下shell:
shell 的菜鳥教程: http://www.runoob.com/linux/linux-shell.html
shell截取字符串: http://www.jb51.net/article/56563.htm
shell 字符串比較: https://www.cnblogs.com/wangkongming/p/4221503.html