Shell – Add text with echo but start with new line if file not empty

echofilesshell-script

I'm trying to create next script

echo "#!/bin/sh" >/script
echo "del x.txt" >>/script

witch is ok if /script file is empty, if not – will append first line to last text

#!/bin/sh
del x.txt#!/bin/sh
del x.txt

If I add an echo empty line first it's ok again if file not empty, but if empty – the script will not be executed

echo "" >>/script
echo "#!/bin/sh" >>/script
echo "del x.txt" >>/script

EDIT:

I will explain exactly what I'm trying to do, on my asuswrt router I want to add a new rule to port forwarding script, witch is firewall-start

echo "#!/bin/sh" >/jffs/scripts/firewall-start
echo "" >>/jffs/scripts/firewall-start
echo "iptables -I INPUT -p tcp --destination-port 3000 -j ACCEPT" >>/jffs/scripts/firewall-start

This will overwrite any text in /jffs/scripts/firewall-start

I want a solution to create script from scratch or to append this lines but starting with new line and not to append text to the last line.
If I start with empty line and the script is empty, will not be executed after because #!/bin/sh should be in the first line

echo "" >>/jffs/scripts/firewall-start
echo "#!/bin/sh" >/jffs/scripts/firewall-start
echo "" >>/jffs/scripts/firewall-start
echo "iptables -I INPUT -p tcp --destination-port 3000 -j ACCEPT"

/jffs/scripts/firewall-start

Best Answer

You can test to see if a file is empty by using unix test -s. Example below...

 if [ -s $file ]
then
   echo "File size is zero"
else
   echo "File size is not zero"
fi
Related Question