shell腳本--檢查文件是否存在
寫一個(gè)腳本,來檢查某個(gè)文件是否存在,如果存在,則輸出它的詳細(xì)信息,如果不存在,則提示輸出文件不存在。在給出這個(gè)腳本之前,先來了解一下如下幾個(gè)命令:文件upload.zip為例
1. # ll -h upload.zip
-rw-r--r-- 1 root root 3.3M 06-28 23:21 upload.zip
2. # file upload.zip
upload.zip: Zip archive data, at least v1.0 to extract
3. # ls -i upload.zip
1427041 upload.zip
4. # df -h upload.zip
文件系統(tǒng) 容量 已用 可用 已用% 掛載點(diǎn)
/dev/hda3 9.5G 5.7G 3.4G 64% /
下面的腳本將把這些命令融合在一起,來顯示一個(gè)文件的詳細(xì)信息。
#!/bin/bash
# This script gives information about a file.
FILENAME="$1"
echo "Properties for $FILENAME:"
if [ -f $FILENAME ]; then
echo "Size is $(ls -lh $FILENAME | awk '{ print $5 }')"
echo "Type is $(file $FILENAME | cut -d":" -f2 -)"
echo "Inode number is $(ls -i $FILENAME | cut -d" " -f1 -)"
echo "$(df -h $FILENAME | grep -v 文件系統(tǒng) | awk '{ print "On",$1", \
which is mounted as the",$6,"partition."}')"
else
echo "File does not exist."
fi
記得要賦予腳本可執(zhí)行權(quán)限哦?。。。?/P>
chomd u+x wenjian.sh
執(zhí)行腳本的結(jié)果如下:
# /jiaoben/wenjian.sh upload.zip
Properties for upload.zip:
Size is 3.3M
Type is Zip archive data, at least v1.0 to extract
Inode number is 1427041
On /dev/hda3, which is mounted as the / partition.
這樣就比我們一個(gè)一個(gè)敲命令來檢查文件的信息要方便多了。
如果對(duì)cut命令不是很了解,可以參考以下說明:
-----------------------------------------------------------------------
-----------------------------------------------------------------------
cut命令可以從一個(gè)文本文件或者文本流中提取文本列。
命令用法:
cut -b list [-n] [file ...]
cut -c list [file ...]
cut -f list [-d delim][-s][file ...]
上面的-b、-c、-f分別表示字節(jié)、字符、字段(即byte、character、field);
list表示-b、-c、-f操作范圍,-n常常表示具體數(shù)字;
file表示的自然是要操作的文本文件的名稱;
delim(英文全寫:delimiter)表示分隔符,默認(rèn)情況下為TAB;
-s表示不包括那些不含分隔符的行(這樣有利于去掉注釋和標(biāo)題)
上面三種方式中,表示從指定的范圍中提取字節(jié)(-b)、或字符(-c)、或字段(-f)。
范圍的表示方法:
M
只有第M項(xiàng)
M-
從第M項(xiàng)一直到行尾
M-N
從第M項(xiàng)到第N項(xiàng)(包括N)
-N
從一行的開始到第N項(xiàng)(包括N)
-
從一行的開始到結(jié)束的所有項(xiàng)
范例:
# cat example
test2
this is test1
# cut -c1-6 example ## print 開頭算起前 6 個(gè)字元
test2
this i
-c m-n 表示顯示每一行的第m個(gè)字元到第n個(gè)字元。例如:
---------file-----------
wokao 84 25000
---------file-----------
# cut -c 1-5,10-25 file
wokao 25000
-f m-n 表示顯示第m欄到第n欄(使用tab分隔)。例如:
---------file-----------
wokao 84 25000
---------file-----------
# cut -f 1,3 file
wokao 25000
我們經(jīng)常會(huì)遇到需要取出分字段的文件的某些特定字段,例如 /etc/password就是通過":"分隔各個(gè)字段的??梢酝ㄟ^cut命令來實(shí)現(xiàn)。例如,
我們希望將系統(tǒng)賬號(hào)名保存到特定的文件,就可以:
cut -d":" -f 1 /etc/passwd > /tmp/users
-d用來定義分隔符,默認(rèn)為tab鍵,-f表示需要取得哪個(gè)字段
如:
使用|分隔
cut -d'|' -f2 1.test>2.test
使用:分隔
cut -d':' -f2 1.test>2.test
這里使用單引號(hào)或雙引號(hào)皆可。
【編輯推薦】