title: Escaping characters in variables inside sed expression
body: <p>So im having an issue where this portion of my script is not working. I'm not sure exactly whats going on, but I get the feeling its because I have not escaped certain characters inside the variables. I tried the following with no luck:</p>
  
  <pre><code>crontab -l | sed "s%$CTMP%\*\/$FREQ \* \* \* \* cd $DIR &amp;&amp; \.\/$SCRIPT%" | crontab -
  </code></pre>
  
  <p>Here is whats in each of the variables:</p>
  
  <p>The CTMP variable is just a line from the crontab file</p>
  
  <pre><code>CTMP='*/5 * * * * cd /home/admin/whatever &amp;&amp; ./test.sh'
  </code></pre>
  
  <p>The <code>FREQ</code> variable is the time in minutes setting of the cron file</p>
  
  <pre><code>FREQ=5
  </code></pre>
  
  <p>The DIR variable is the current working directory</p>
  
  <pre><code>DIR='/home/admin/whatever'
  </code></pre>
  
  <p>And the SCRIPT variable is just the script file name</p>
  
  <pre><code>SCRIPT='test.sh'
  </code></pre>
  
  <p>I feel like the issue is the sed statement is not updating the crontab file because it's not escaping the characters it needs to inside these variables above.</p>
  
  <p>Is that correct or is something else wrong?</p>
  
  <p><strong>* UPDATE *</strong></p>
  
  <pre><code>CTMPESC=$(sed 's/[\*\.]/\\&amp;/g' &lt;&lt;&lt;"$CTMP")
  DIRESC=$(sed 's/[\*\.]/\\&amp;/g' &lt;&lt;&lt;"$DIR")
  SCRIPTESC=$(sed 's/[\*\.]/\\&amp;/g' &lt;&lt;&lt;"$SCRIPT")
  crontab -l | sed "s%$CTMPESC%\*/$FREQ \* \* \* \* cd $DIRESC &amp;&amp; \./$SCRIPTESC%" | crontab -
  </code></pre>
  
  <p><strong>* UPDATE *</strong></p>
  
  <p>Here is the crontab output</p>
  
  <pre><code>*/10 * * * * cd /home/administrator/anm-1.5.0 */7 * * * * cd /home/administrator/anm-1.5.0 &amp;&amp; ./anm.sh*/7 * * * * cd /home/administrator/anm-1.5.0 &amp;&amp; ./anm.sh ./anm.sh
  </code></pre>
  
  <p>and I also echoed the three escaped variables just to troubleshoot and here they are:</p>
  
  <pre><code>\*/7 \* \* \* \* cd /home/administrator/anm-1\.5\.0 &amp;&amp; \./anm\.sh
  /home/administrator/anm-1\.5\.0
  anm\.sh
  </code></pre>
  
  <p>The three escaped variables actually look good.</p>
  
  <p><strong>* UPDATE *</strong></p>
  
  <p>Cron file before the replace:</p>
  
  <pre><code>*/10 * * * * cd /home/administrator/anm-1.5.0 &amp;&amp; ./anm.sh
  </code></pre>
  
  <p>Cron file after the replace:</p>
  
  <pre><code>*/7 * * * * cd /home/administrator/anm-1.5.0 */10 * * * * cd /home/administrator/anm-1.5.0 &amp;&amp; ./anm.sh*/10 * * * * cd /home/administrator/anm-1.5.0 &amp;&amp; ./anm.sh ./anm.sh
  </code></pre>
  
  <p>See all the extra junk that gets thrown in there somehow?</p>