作業1
撰寫腳本exe1,該腳本接收一個命令列引數,并根據其型別做以下操作:
- 若引數為普通檔案,則顯示其內容
- 若引數為壓縮檔案,則解壓縮(如同目錄下有同名檔案則放棄)
- 若引數為目錄,則將其歸檔并壓縮(如已有同名壓縮檔案則放棄)
- 若引數不存在,給出錯誤提示并退出
#!/bin/bash
str=$1
len=${#str}
let len=$len-3
if [ -e $1 ]
then
if [ -f $1 ]
then
if [ ${str:$len:3} = ".gz" ]
then
gzip -d $1
else
cat $1
fi
elif [ -d $1 ]
then
file=$1".tar.gz"
if [ ! -e $file ]
then
tar -czvf $file $1
fi
fi
else
echo "No such file! Error!"
fi
注意:
- test陳述句的空格
- 參考引數要寫
$ - 整數計算,要用let操作
- 用{}進行的變數操作不需要
$參考,只需要寫變數名 elif也要加then
作業2
撰寫腳本exe2,由用戶輸入一組數(以end表示輸入結束),輸出這些數的和,結果保留2位小數,要求使用函式做輸入型別檢查,并給出錯誤提示資訊,
#!/bin/bash
if_is_legal(){
if [[ $1 = [0-9]*\.[0-9]* ]] || [[ $1 = [0-9]*[^.a-zA-Z] ]] || [[ $1 = [0-9] ]]
then
return 0
else
return 1
fi
}
read num
sum=0
while [ $num != "end" ]
do
if if_is_legal $num
then
sum=$(echo "$sum+$num" | bc)
else
echo "type error! please input again!"
fi
read num
done
echo "scale=2;$sum/1.0" |bc
注意:
- 函式如何傳參
- 函式回傳值的寫法
- 浮點運算的寫法
作業3
撰寫腳本exe3,該腳本對比兩個目錄dir1和dir2(通過引數給出),將dir2中符合下列條件的檔案復制到dir1,并將每一條復制記錄存盤到檔案record中:
- 該檔案不在dir1中
- 該檔案比dir1中的同名檔案更新
#!/bin/bash
for item in `ls $2`
do
echo $item
if [ -e $1"/"$item ]
then
if [ $2"/"$item -nt $1"/"$item ]
then
cp $2"/"$item $1
echo "replace $item in $1" >> record
fi
else
cp $2"/"$item $1
echo "copy $item from $2 to $1" >> record
fi
done
echo "done successfully!"
注意:
- 檔案名的拼接
for回圈的使用
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/199218.html
標籤:python
