TimeLinux1

Wednesday, March 6, 2013

Heredoc to automate shell scripts

Ever wondered if there was a way to automate passing multiple bash commands to run non interactively?
For instance, if you wanted to create a shell script to start vi editor, get into insert mode and populate some commands based on some condition and then escape, save and exit out of the editor all while being in the shell script--how would you do it?

The answer is what is called heredoc. The concept of heredoc comes from C programming language and which was later borrowed into Unix/Linux tradition. Basically what a heredoc does is to accept commands from a stream starting with a start-signature and ending with the same signature. So all the commands or interactions with the shell between those start-end signatures are non-interactive.
For a more detailed discussion visit heredoc pages here and here.

An Example:

#-------------


[root@redhat2 mrinal]# cat myscript
#!/bin/bash

tfile=$1

vi $tfile << bye                      /* start vi with a file argument $tfile by user & start signature = bye*/
i                                              /* invoke 'insert' mode of vi */
echo `date`                              /* run a command */
`uname -a`                              /* run another command */
`ls -l`
^[                                            /* escape to command mode of vi, passed by Ctrl+v on keyboard */
wq                                          /* save file */
bye                                      /* end non interactive mode when sees the signature = bye */

#------------

The above shell script will open vi non-interactively and run a bunch of commands between the start-end signature, here in our case the word 'bye'. It could be anything you choose, as long the start and end signatures are the same. 

No comments:

Post a Comment