NFS 客戶端的配置雖然不複雜,但每次手動操作仍顯繁瑣。這次我們用一支腳本完成三件事:自動檢測並安裝 nfs-common、自動建立掛載目錄並掛載,以及確保開機自動掛載。
#!/bin/bash
source ../../common/tool.sh
nfsClient="nfs-common"
nfsServerFolder=10.112.18.158:/opt/share
nfsClientFolder=~/test_nfs_dir
hasDpkg $nfsClient
r=$?
if [ $r -eq 1 ]
then
echo "$nfsClient was installed"
else
echo "$nfsClient was not installed"
apt-get install $nfsClient
fi
# 建立本地掛載目錄並掛載
createFolder $nfsClientFolder
mount -t nfs4 $nfsServerFolder $nfsClientFolder
mountString="$nfsServerFolder $nfsClientFolder nfs rsize=8192,wsize=8192,timeo=14,intr"
searchString="$nfsServerFolder"
mountConfigFile="/etc/fstab"
findStringInFile $searchString $mountConfigFile
m=$?
if [ $m -eq 1 ]
then
echo "auto mount was configured"
else
echo "auto mount was not configured, configuring..."
echo $mountString >> $mountConfigFile
fi
腳本引入了一個新的工具函數 findStringInFile,同樣放在 tool.sh 中,用來判斷某個字串是否存在於指定檔案裡,找到回傳 1,找不到回傳 0:
#$1 search string
#$2 file path
#return 1 if found
#return 0 if not found
function findStringInFile {
h=`grep "$1" $2`
echo "h: $h"
if [ -n "$h" ]
then
return 1
else
return 0
fi
}
透過 hasDpkg、createFolder、findStringInFile 這幾個可重複利用的小函數,NFS 客戶端的部署變得既自動又具幂等性——重複執行也不會產生重複的 fstab 配置,這正是自動化腳本實務中很值得追求的品質。