2009年12月22日 星期二

Shell Script Programming II

5.設計一個名為getmax的script,使其可以接收兩個數字參數,將較大的數顯示出來,如果都一樣大,則顯示都一樣大。

$ ./maxmin 18 15
max = 18
$
$ ./maxmin 15 15
Equals
$
----



6.設計一個名為checkfile的script,使其可以接收一個檔案名稱作為參數,
若此名稱不是目前工作目錄的檔案或目錄,則顯示此名稱不存在,如果是檔案,則顯示其檔案內容,如果是一目錄則顯示此目錄內的清單。
$ checkfile 名稱
----


7.設計一個名為newerfile的script,使其可以接收兩個檔案名稱作為參數,並將日期較新的檔案名稱顯示出來。
$ newerfile file1.txt file2.txt
file2.txt 較新
----


8.設計一個名為avglen的script,使其可以接收一個檔案名稱(文字檔)作為參數,計算此檔平均每一列有多少bytes。
提示:使用wc -l < 檔名; 用man查一下wc的用法
$ avglen yang.txt
平均每列: 348 bytes
----


9.設計一個名為createtodayfile的script,以touch指令產生一個檔案,檔名中含有今天的日期,例如myfile20090706.txt。
date +%Y...., 其餘date的日期格式, 請以man指令查詢
----


10.設計一個名為addfiles的script,可自命令列讀取參數產生檔案allfile,如下,每加入一個檔案,隔2秒,如果重覆執行,則覆蓋原檔案。
原始檔案:
$ cat filea.txt
aaaaa
$ cat fileb.txt
bbbbb
$ cat filec.txt
ccccc


執行程式:
$ ./addfiles allfile.txt filea.txt fileb.txt filec.txt


結果:
$ cat allfile.txt
--2009-09-08 16:25:33
aaaaa
--2009-09-08 16:25:35
bbbbb
--2009-09-08 16:25:37
ccccc









5.
#!/bin/sh


if [ $1 -gt $2 ]
  then
        echo "$1 VS $2 -> Max is $1"
elif [ $1 -lt $2 ]
  then
        echo "$1 VS $2 -> Max is $2"
else
        echo "$1 VS $2 -> Equals"
fi

exit 0


6.
#!/bin/sh
file=$1
if [ -f "$file" ]
 then
       echo "`cat $file`"
elif [ -d "$file" ]
 then
       echo "`ls -l $file`"
else
       echo "No such file or directory"
fi
exit 0


7.
#!/bin/sh


if [ $1 -nt $2 ]
then
       echo "$1 VS $2 = New file is $1"
elif [ $1 -ot $2 ]
then
       echo "$1 VS $2 = New file is $2"
else
       echo "No such file. Please check!"
fi

exit 0


8.
#!/bin/sh


x=`wc -c < $1`
y=`wc -l < $1`
echo total is "$x"bytes
echo line is "$y"
echo "average is $((x/y))bytes."


 9.
#!/bin/sh
x=`date +%Y%m%d`
echo "creat a file ---> myfile$x".txt
`touch myfile"$x".txt`


10.
#!/bin/sh


echo 1.touch "$1"
touch $1
y=`date +%Y`
m=`date +%m`
d=`date +%d`
t=`date +%T`

echo --$y-$m-$d\ $t > $1
cat $2 >> $1
sleep 2
echo "run1"
t=`date +%T`
echo --$y-$m-$d\ $t >> $1
cat $3 >> $1
sleep 2
echo "run2"
t=`date +%T`
echo --$y-$m-$d\ $t >> $1
cat $4 >> $1
exit 0

沒有留言:

張貼留言