How to read * in a variable in shell script??

hi,

i have a text file which conatins some fields delimited by space. some fields contains * as entries.

cron_file.txt

0 * * * *
0 3 * * *

i want to read each line 1 by 1 and store each field in seperate variables n a shell script.

i am unable to read the field that contains a *. how can i read * in a variable.

script

while read line
do
        MINUTE=`echo $line | cut -d " " -f 1`
        HOUR=`echo $line | cut -d " " -f 2`
        DAY_OF_MONTH=`echo $line | cut -d " " -f 3`
        MONTH=`echo $line | cut -d " " -f 4`
        DAY_OF_WEEK=`echo $line | cut -d " " -f 5`
        
        echo "MINUTE = {$MINUTE}"
        echo "HOUR = {$HOUR}"
        echo "DAY_OF_MONTH = {$DAY_OF_MONTH}"
        echo "MONTH = {$MONTH}"
        echo "DAY_OF_WEEK = {$DAY_OF_WEEK}"
done < cron_file.txt

Instead of reading all in one, try:

while read MINUTE HOUR DAY_OF_MONTH MONTH DAY_OF_WEEK REST_OF_LINE

then you won't need all those cut commands.

(the answer to your question, incidentally, is to quote variables to prevent shell expansion of characters like *)

i.e.

echo "$line" | cut -d " " -f 3

modified my script

while read MINUTE HOUR DAY_OF_MONTH MONTH DAY_OF_WEEK REST
do

        echo "MINUTE = {$MINUTE}"
        echo "HOUR = {$HOUR}"
        echo "DAY_OF_MONTH = {$DAY_OF_MONTH}"
        echo "MONTH = {$MONTH}"
        echo "DAY_OF_WEEK = {$DAY_OF_WEEK}"
        echo "REST = {$REST}"

done < cron_file.txt

as you know cron tab entries will contain shell script name to be executed. i dnt want to capture that. how? i have used "REST" for storing any other fields.. is it ok

It's perfect! I had added REST_OF_LINE to my post after submitting it. That'll pick up everything after the last cron time field.

1 Like