2016-12-16 59 views
1

我創建了一個bash腳本,用於修改RHEL服務器中打開文件的ulimit。sed無法使用bash腳本對文件中的某一行進行評論

所以我已經讀取文件/etc/security/limits.conf中的行,如果'*'域的打開文件的軟限制/硬限制小於10000,我正在評論行並添加一個新行行軟/硬限制爲10000.

腳本按設計工作,但在腳本中註釋行的sed命令不起作用。

請在下面找到完整的腳本: -

#!/bin/sh 
#This script would be called by '' to set ulimit values for open files in unix servers. 
# 
configfile=/etc/security/limits.conf 
help(){ 
echo "usage: $0 <LimitValue>" 
echo -e "where\t--LimitValue= No of files you want all the users to open" 
exit 1 
} 
modifyulimit() 
{ 
grep '*\s*hard\s*nofile\s*' $configfile | while read -r line ; do 
     firstChar="$(echo $line | xargs | cut -c1-1)" 
     if [ "$firstChar" != "#" ];then 
     hardValue="$(echo $line | rev | cut -d ' ' -f1 | rev)" 
      if [[ "$hardValue" -ge "$1" ]]; then 
      echo "" 
      else 
      sed -i -e 's/$line/#$line/g' $configfile 
      echo "*   hard  nofile   $1" >> $configfile 
      fi 
     else 
      echo "" 
     fi 
    done 

grep '*\s*soft\s*nofile\s*' $configfile | while read -r line ; do 
     firstChar="$(echo $line | xargs | cut -c1-1)" 
     if [ "$firstChar" != "#" ];then 
     hardValue="$(echo $line | rev | cut -d ' ' -f1 | rev)" 
      if [[ "$hardValue" -ge "$1" ]]; then 
      echo "" 
      else 
      sed -i -e 's/$line/#$line/g' $configfile 
      echo "*   hard  nofile   $1" >> $configfile 
      fi 
     else 
      echo "" 
     fi 
    done 
} 
deleteEofTag(){ 
sed -i "/\b\(End of file\)\b/d" $configfile 
} 
addEofTag() 
{ 
echo "#################End of file###################" >> $configfile 
} 
#-------------Execution of the script starts here ---------------------- 
if [ $# -ne 1 ]; 
then 
help 
else 
modifyulimit $1 
deleteEofTag 
addEofTag 
fi 

命令SED -i -e 'S/$線/#$線/ G' 從終端執行時$ CONFIGFILE工作絕對罰款和它正在評論該行,但是它在我從unix shell腳本執行它時不起作用。

回答

0

插不單引號 使用雙引號工作,並嘗試

SED -i -e 'S/$線/#$線/ G'

sed -i -e "s/$line/#$line/g" 
+0

感謝它的工作。 :) –

0

還你可能會嘗試: sed -i -es/$ {line} /#$ {line}/g 因爲這會告訴腳本採用變量的值而不是變量。