Search code examples
linuxshellcroncron-taskcronexpression

How to install multiple cron jobs?


the below code for installing multiple cron jobs at a same time using shellscript

#!/bin/bash
    file="/home/admin/Desktop/crontab.sh"
    file1="/home/admin/Desktop/crontab1.sh"
    file2="/home/admin/Desktop/crontab2.sh"
    file3="/home/admin/Desktop/crontab3.sh"
    echo "$1 $2 $3 $4 $5 $file" >> cron.new
    echo "$6 $7 $8 $9 $10 $file1" >> cron.new
    echo "$11 $12 $3 $14 $15 $file2" >> cron.new
    echo "$16 $17 $18 $19 $25 $file3" >> cron.new
    cat cron.new
    crontab cron.new

Solution

  • Bash positional parameters start from 0 end at 9. And so you have to send all your positional parameters as a single argument. i.e enclose all parameters inside a single-quote or double-quote.

    Below program will help you.

    #!/bin/bash
    
    files=("/home/admin/Desktop/crontab.sh" "/home/admin/Desktop/crontab1.sh" "/home/admin/Desktop/crontab2.sh" "/home/admin/Desktop/crontab3.sh")
    args=($(echo $1))
    
    for file in ${files[@]}
    do
        list=(${args[@]:0:5})
        args=(${args[@]:5})
    
        for i in $(seq 0 4)
        do
            cmd="${cmd} ${list[$i]}"
        done
    
        echo "$cmd $file"
        cmd=''
    done
    

    Output:

    $ ./test.sh '1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20'
     1 2 3 4 5 /home/admin/Desktop/crontab.sh
     6 7 8 9 10 /home/admin/Desktop/crontab1.sh
     11 12 13 14 15 /home/admin/Desktop/crontab2.sh
     16 17 18 19 20 /home/admin/Desktop/crontab3.sh
    

    Here the numbers are passed as a single argument by enclosing them within single-quote. The file names are placed inside an array for easy access.