1

I am writing a script to fix a missing 'F' letter in a mail log file. The mail log file is continuously updating. I am getting a file name, after that I am doing 'sudo su' to get superuser access. Inside sudo, I am fixing a that missing 'F'. However, I am unable to use that file name inside sudo block. Please can anyone help me how I can export these shell variables inside sudo? I tried using export but its not working. The code block I have created is as follows-

 #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;
2

You quoted the heredoc delimiter:

sudo su<<'HERE'

Variables in a heredoc are not expanded if the delimiter is quoted. From the docs:

If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion, the character sequence \newline is ignored, and ‘\’ must be used to quote the characters ‘\’, ‘$’, and ‘`’.

Just use:

sudo su <<HERE

Example:

$ a=1; cat <<HERE
> $a
> HERE
1
$ a=1; cat <<'HERE'
> $a
> HERE    
$a

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.