0

How can I use grep to extract a line from a crontab file and store it to a variable? This is not working:

CTMP=$(crontab -l | grep $SCRIPT)

$SCRIPT is another variable defined within the program. Example anm.sh which is what I am searching for in the crontab to identify the line I need to extract.

Thanks!

* UPDATE *

Its doing something very strange. I tried this:

CTMP=$(crontab -l | grep "anm.sh")

This is what my crontab looks like:

*/17 * * * * cd /home/administrator/anm-1.5.0 && ./anm.sh

However when I echo out CTMP it randomly has a bunch of info that makes no sense. Somehow its pulling the names of directories in the current working directory. Here was the output:

*/17 anm.cfg anm.sh databases logs tmp anm.cfg anm.sh databases logs tmp anm.cfg anm.sh databases logs tmp anm.cfg anm.sh databases logs tmp cd /home/administrator/anm-1.5.0 && ./anm.sh

Those directory names do exist, but why the heck is it pulling those directory names???

All I need to do is get that line from the crontab file stored to the variable CTMP

Thanks

Atomiklan
  • 5,164
  • 11
  • 40
  • 62

2 Answers2

2

I think the problem is in the ECHO statement.

The variable is filled right when you do crontab -l | grep "anm.sh":
CTMP="*/17 * * * * cd /home/administrator/anm-1.5.0 && ./anm.sh"

echo $CTMP
<<bunch of dir names>>

echo "$CTMP"
*/17 * * * * cd /home/administrator/anm-1.5.0 && ./anm.sh

quote the variable when echoing.

Alessandro Da Rugna
  • 4,571
  • 20
  • 40
  • 64
  • That did it! Thank you! Now I just need to figure out the bigger issue I'm having with my sed command that handles this variable. Maybe you can take a look at this one too. Here is the bigger question: http://stackoverflow.com/questions/17267904/cron-job-not-being-updated – Atomiklan Jun 24 '13 at 08:57
0

You probably want to turn off globbing (the asterisks are being interpreted).

Probably, you should also use quotes.

CTMP="$(set -f; crontab -l | grep 'anm.sh')"
Marki
  • 660
  • 8
  • 24
  • @Marki - you've identified the cause of the problem, but you need to suppress globbing when CTMP is expanded (i.e. by $CTMP) ... not when it is set. – Stephen C Jun 24 '13 at 11:21
  • @StephenC you're completely right. I had globbing already suppressed in the main shell therefore it worked on my box. Duh. – Marki Jun 24 '13 at 12:24