我正在编写一个脚本来修复邮件日志文件中缺失的“F”字母。邮件日志文件不断更新。我得到了一个文件名,然后我执行“sudo su”来获得超级用户访问权限。在 sudo 中,我正在修复缺失的“F”。但是,我无法在 sudo 块中使用该文件名。请问有人能帮我如何在 sudo 中导出这些 shell 变量吗?我试过使用 export,但没有用。我创建的代码块如下-
#Script to solve F issue
#----------------------------------------
#By Kapil Shirsath
#----------------------------------------
cd /var/spool/mail #mail files reside in mail folder
echo "Entered in mail folder"
filename=`ls -lrt 99999*| sort -k 5 -rn | head -1 | tr -s " " "," | cut -d "," -f "8"` # this will list the file with maximum size`
echo "File with maximum size is $filename"
echo "----------------------------------------------------"
echo "Is it the file expected?(y/n)"
read choice
if test $choice == "n"
then
echo "Exiting...."
exit;
fi;
c=1
while [ $c -le 5 ]
do
ls -lrt $filename
echo $filename
sleep 3
c=`expr $c + 1`
done
echo "---------------------------------------------------"
sudo su<<'HERE' #this will give you super user permissions
echo "Got root access"
echo "First line of the file is as below :"
head -1 $filename
echo "---------------------------------------"
firstline=`head -1 $filename`
echo "Repeat : $firstline"
echo $firstline | grep ^"rom" >/dev/null
if test $? -eq 0
then
ex -s $filename <<'EOF'
1s/^/F/
:wq
EOF
echo "F issue fixed!"
HERE
c=1
while [ $c -le 5 ]
do
ls -lrt $filename
sleep 3
c=`expr $c + 1`
done
echo "---------------------------------------------------"
else
echo "Not finding the missing 'F' ! !! Kindly check with your system "
exit;
fi;
答案1
您引用了 heredoc 分隔符:
sudo su<<'HERE'
如果分隔符被引用,则 heredoc 中的变量不会扩展。来自文档:
如果任何字符单词被引用,分隔符是删除引号的结果单词,并且此处文档中的行不会被扩展。如果单词不加引号,此处文档的所有行都将经过参数扩展、命令替换和算术扩展,字符序列
\newline
将被忽略,并且\
必须使用 ' ' 来引用字符 '\
'、'$
' 和 '`
'。
只需使用:
sudo su <<HERE
例子:
$ a=1; cat <<HERE
> $a
> HERE
1
$ a=1; cat <<'HERE'
> $a
> HERE
$a