How to give user input in cronjob script

In this tutorial, we will explain how to give user input in cronjob script.

How to give user input in cronjob script

There are two-ways to do this:

  1. Simply modify your script so it does not need user input.
  2. Feed the script its required input from a file, via “<” 
If the script is expected password as a user input then don’t use option 2, this option is easy but not at all secure.

Example for option 2: 

I am having a simple script which will print “hello world” in different color as per the user input.

#!/bin/bash

red=$'\e[1;31m'

grn=$'\e[1;32m'

yel=$'\e[1;33m'

blu=$'\e[1;34m'

end=$'\e[0m'

printf  "\n [1] : Print Hello World in Green color \n \

[2] : Print Hello World in yellow color \n \

[3] : Print Hello World in blue color \n \

[4] : Print Hello World in Red color \n \

[e] : Exit \n "

#read user_input

read -p "Enter choice:  " ch

for i in ${ch}

do

  if [ "$i" == "1" ]; then

    printf "$grn Hello World $end \n"

  else if [ "$i" == "2" ]; then

    printf "$yel Hello World $end \n"

  else if [ "$i" == "3" ]; then

    printf "$blu Hello World $end \n"

  else if [ "$i" == "4" ]; then

    printf "$red Hello World $end \n"

  else if [ "$i" == "e" ]; then

    break

fi

fi

fi

fi

fi

done

To schedule this in crontab with user input, easy way to create a simple text file with your Input and this file will be given as stdin to the script. 

$ cat input-file.txt
1 2 3

So I have created text file “input-file.txt”. This file is given as stdin to the cronjob script.

$ crontab -l

0 * * * * /usr/bin/sh -c "/home/centos/test-color.sh < input-file.txt"

Sample Output:

$ /usr/bin/sh -c "/home/centos/test-color.sh < input-file.txt"

 [1] : Print Hello World in color Green

 [2] : Print Hello World in color yellow

 [3] : Print Hello World in color blue

 [4] : Print Hello World in color Red

 [e] : Exit

  Hello World

 Hello World

 Hello World

$ cat input-file.txt

1 2 3

$

Screenshot of sample output:

 

Another example for option 2: 

If you need only confirmation (yes) in your script, then crontab can look like this:

0 * * * * /bin/sh -c “yes | /foo/bar/my_command”

0 * * * * /bin/sh -c “yes | /path-of-script/script”

This is the end of topic – How to give user input in cronjob script.

See Also:

Google Cloud Blogs

Linux Blogs

AWS Cloud Blogs

Database Blogs

DevOps Blogs

Interview Questions & Answers

Docker Blogs