shell指令碼 檢查檔案是否存在

2022-08-24 11:54:15 字數 2621 閱讀 1347

from:

寫乙個指令碼,來檢查某個檔案是否存在,如果存在,則輸出它的詳細資訊,如果不存在,則提示輸出檔案不存在。在給出這個指令碼之前,先來了解一下如下幾個命令:檔案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

檔案系統              容量  已用 可用 已用% 掛載點

/dev/hda3             9.5g  5.7g  3.4g  64% /

下面的指令碼將把這些命令融合在一起,來顯示乙個檔案的詳細資訊。

#!/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 '')"

echo "type is $(file $filename | cut -d":" -f2 -)"

echo "inode number is $(ls -i $filename | cut -d" " -f1 -)"

echo "$(df -h $filename | grep -v 檔案系統 | awk '')"

else

echo "file does not exist."

fi記得要賦予指令碼可執行許可權哦!!!!

chomd u+x wenjian.sh

執行指令碼的結果如下:

# /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.

這樣就比我們乙個乙個敲命令來檢查檔案的資訊要方便多了。

cut命令可以從乙個文字檔案或者文字流中提取文字列。

命令用法:

cut -b list [-n] [file ...]

cut -c list [file ...]

cut -f list [-d delim][-s][file ...]

上面的-b、-c、-f分別表示位元組、字元、字段(即byte、character、field);

list表示-b、-c、-f操作範圍,-n常常表示具體數字;

file表示的自然是要操作的文字檔案的名稱;

delim(英文全寫:delimiter)表示分隔符,預設情況下為tab;

-s表示不包括那些不含分隔符的行(這樣有利於去掉注釋和標題)

上面三種方式中,表示從指定的範圍中提取位元組(-b)、或字元(-c)、或字段(-f)。

範圍的表示方法:

m只有第m項

m-從第m項一直到行尾

m-n從第m項到第n項(包括n)

-n從一行的開始到第n項(包括n)

從一行的開始到結束的所有項

範例:# cat example

test2

this is test1

# cut -c1-6 example ## print 開頭算起前 6 個字元

test2

this i

-c m-n 表示顯示每一行的第m個字元到第n個字元。例如:

---------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

我們經常會遇到需要取出分字段的檔案的某些特定字段,例如 /etc/password就是通過":"分隔各個欄位的。可以通過cut命令來實現。例如,

我們希望將系統賬號名儲存到特定的檔案,就可以:

cut -d":" -f 1 /etc/passwd > /tmp/users

-d用來定義分隔符,預設為tab鍵,-f表示需要取得哪個字段

如:使用|分隔

cut -d'|' -f2 1.test>2.test

使用:分隔

cut -d':' -f2 1.test>2.test

這裡使用單引號或雙引號皆可。

Shell指令碼判斷檔案是否存在

例項一 bin sh 判斷檔案是否存在 這裡的 x 引數判斷 mypath是否存在並且是否具有可執行許可權 if x mypath then mkdir mypath fi 這裡的 d 引數判斷 mypath是否存在 if d mypath then mkdir mypath fi 這裡的 f引數判...

shell指令碼判斷檔案是否存在

檔案不存在則建立 if d data then mkdir data else echo 資料夾已經存在 fi檔案存在則刪除 if f data filename then echo 檔案不存在 else rm f data filename fi判斷資料夾是否存在 if d data then e...

Python 如何檢查檔案是否存在

在python中,我們可以使用os.path.isfile 或pathlib.path.is file python 3.4 來檢查檔案是否存在。python 3.4的新功能 from pathlib import path fname path c test abc.txt print fname...