echo 和变量扩展

echo 和变量扩展

我有一个脚本来生成脚本:

echo '#!/bin/sh'>>rule-1  
echo 'compare() (IFS=" "'>>rule-1  
echo '  exec awk "BEGIN{if (!($*)) exit(1)}"'>>rule-1  
echo ')'>>rule-1  
echo '#Bepaal  percentage memory used.'>>rule-1  
echo "PERC_MEM_USED=$(free | grep Mem | awk '{print $3*100/$2}')">>rule-1  
echo "echo 'Percentage memory used :'">>rule-1  
echo 'echo $PERC_MEM_USED'>>rule-1  
echo 'if compare "$PERC_MEM_USED > 90";'>>rule-1  
echo 'then'>>rule-1  
echo "   echo 'Percentage memory is high.'">>rule-1 
echo '   # PSM data'>>rule-1  
echo "   echo  '(PSM)'">>rule-1  
echo "   echo '(CATEGORY)WARNING(/CATEGORY)'">>rule-1  
echo "   echo '(MESSAGE)Percentage memory is high '$PERC_MEM_USED', please contact ---(MESSAGE)'">>rule-1  
echo "   echo '(/PSM)'">>rule-1  
echo 'fi'>>rule-1

当我执行它时,生成的脚本是:

#!/bin/sh  
compare() (IFS=" "  
  exec awk "BEGIN{if (!($*)) exit(1)}"  
)  
#Bepaal  percentage memory used.  
PERC_MEM_USED=11.9055  
echo 'Percentage memory used :'  
echo $PERC_MEM_USED  
if compare "$PERC_MEM_USED > 90";  
then  
   echo 'Percentage memory is high.'  
   echo '(PSM)'  
   echo '(CATEGORY)WARNING(/CATEGORY)'  
   echo '(MESSAGE)Percentage memory is high '', please contact ---(MESSAGE)'  
   echo '(/PSM)'  
fi  

该变量$PERC_MEM_USED未在行中扩展(MESSAGE)。有什么想法吗?

答案1

该变量在生成脚本中用双引号引起来,因此在运行外部echo.反斜杠美元符号以防止扩展。另外,您似乎希望在执行生成的脚本时运行命令替换,但它当前在生成脚本时运行。要解决这个问题,您需要反斜杠分配行上的所有美元符号。

此外,您可以将整个块括在大括号中,并在结束括号后>>rule-1添加一个>> rule-1(或者可能?) ,而不是附加到每一行。>

另外,如果您切换到 HERE 文档,则也不必在每一行上重复回显和引号。

#!/bin/bash
cat <<'EOF' > rule-1
#!/bin/sh
compare() (IFS=" "
  exec awk "BEGIN{if (!($*)) exit(1)}"
)
#Bepaal  percentage memory used.
PERC_MEM_USED=$(free | grep Mem | awk '{print $3*100/$2}')
echo 'Percentage memory used :'
echo $PERC_MEM_USED
if compare "$PERC_MEM_USED > 90";
then
   echo 'Percentage memory is high.'
   # PSM data
   echo  '(PSM)'
   echo '(CATEGORY)WARNING(/CATEGORY)'
   echo '(MESSAGE)Percentage memory is high '$PERC_MEM_USED', please contact ---(MESSAGE)'
   echo '(/PSM)'
fi
EOF

答案2

谢谢乔罗巴,

该变量在生成脚本中用双引号引起来,因此在运行外部 echo 时它会被扩展。反斜杠美元符号以防止扩展。另外,您似乎希望在执行生成的脚本时运行命令替换,但它当前在生成脚本时运行。要解决这个问题,您需要反斜杠分配行上的所有美元符号。 ....这成功了:)

相关内容