Linux-Shell腳本練習

#Linux–Shell腳本練習

  1. 編寫一個腳本,計算n以內的奇數和:

    #!/bin/bash
    #求n以內的奇數和
    #讀取一個數n,-p用於向用戶展示提示信息
    read -p "please input a number n:" n
    sum=0
    for i in `seq 1 $n`
    do   
    if [[ $i%2 -ne 0 ]]; 
    	then sum=$[$sum*$i]
    fi
    done
    echo "sum=$sum"
    
    

    發生過的錯誤:

    1. ./sum.sh:行6: 未預期的符號 then' 附近有語法錯誤 ./sum.sh:行6:then sum=sum+sum+i’

    原因:0後面少了一個空格

    1. ./sum.sh:行6: 0+seq 1 $n: 表達式中有語法錯誤 (錯誤符號是 “1 $n”)

    原因:反引號打成了單引號

    1. ./sum.sh: 第 8 行:[: 1%2: 期待整數表達式
      ./sum.sh: 第 8 行:[: 2%2: 期待整數表達式

    原因:if語句少了一箇中括號(if [ $i%2 -ne 0 ])

    2 編寫一個腳本,將一個目錄下的文件打包備份。

    #!/bin/bash
    path='/home/rmx'
    cd ${path}
    
    for file in `ls`
    do
      fileSize=`ls -l ${file}|awk '{print $5}'`
      if [[ ${fileSize} -lt 5210 ]]
         then fileList="$fileList $file"  
    fi
    done
    tar -zcvf fileList.tar.gz $fileList
    

    3 編寫一個腳本,接受用戶輸入的文件,如果該文件是普通文件。就把它複製到當前文件夾,並且修改名稱爲back。如果是設備文件,就刪除它。

    #!/bin/bash
    
    read -p "input:" file
    if [ -f $file ]
    then echo "It is a normal file" 
    cp $file .
    mv $file back
    elif [ ! -f $file ] && [ ! -d $file ]
    then echo "It is a device file "
    rm -rf $file
    fi
    

34 17 * * 4,5,6 /usr/bin/tar -czvf backup.tar.gz /home/rmx/logs
04 13 * * 4,5,6 cp -r /home/rmx /home/temp2
08 13 * * 6 shutdown -r +5 #重啓系統

系統在十分鐘後關機並且馬上重新啓動: # shutdown –r +10

系統馬上關機並且不重新啓動:# shutdown –h now

系統重新啓動總結:reboot,init 6,shutdown -r now

系統關機總結:init 0, shutdown -h now, half

發佈了71 篇原創文章 · 獲贊 40 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章