here-document Code Block

Published: by

  • Categories:

A here document is a special-purpose code block. It uses a form of I/O redirection to feed a command list to an interactive program or a command.

Hard to digest!! Lets take an easy example. Suppose, you have a simple program which asks user to input 2 numbers and displays its sum as output:-

#include
int main()
{
    int a,b;
    scanf("%d",&a);
    scanf("%d",&b);
    printf("Sum of numbers is: %d\n",a+b);
    return 0;
}

Suppose, you want to run this program with some pre-defined input everytime. You cannot actually automate it bcos the input is asked from the user which is meant to be entered by the keyboard.. There is the otherway round by giving input through here-document…

#!/bin/sh
num1=1
num2=10
./a.out << EOF
$num1
$num2
EOF

Testrun:-

shadyabhi@shadyabhi-desktop:~/c$ ./input.sh Sum of numbers is: 11

You can also do something like:-

shadyabhi@shadyabhi-desktop:~/c$ ./a.out < > 1

2 EOF Sum of numbers is: 3 shadyabhi@shadyabhi-desktop:~/c$

Read more about here-document here. ere-docs.html)