Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Bash 腳本編程(十七):NFS 客戶端自動化部署

NFS 客戶端的配置雖然不複雜,但每次手動操作仍顯繁瑣。這次我們用一支腳本完成三件事:自動檢測並安裝 nfs-common、自動建立掛載目錄並掛載,以及確保開機自動掛載。

腳本要完成的三件事

  1. 自動檢測並安裝 nfs-common。
  2. 自動建立本地目錄並執行掛載。
  3. 檢查 /etc/fstab 是否已有相關配置,若無則寫入,確保下次開機能自動掛載。

install.sh 腳本

#!/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 函數

腳本引入了一個新的工具函數 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 配置,這正是自動化腳本實務中很值得追求的品質。

Copyright © Linux教程網 All Rights Reserved