Search This Blog

Sunday, March 30, 2014

How to automatically prefill command on the Linux bash

Linux Bash is one of the most famous Linux shells. It offers a great number of features like for example spawning and controlling process, redirecting streams, supporting scripts and a flexible way to control you editing line.

Problem

How to automatically pre-populate a command on the shell after prompt.

Solution description

The shell has tree default streams: stdout, stdin and stderr. By manipulating the stdin of the process we can simulate typing a command.

Reference implementation

The original script can be found here: https://github.com/rtomaszewski/experiments/blob/master/type-command.c

Demonstration
  • Compile first the program
gcc -o type-command type-command.c
  • Run for the firs time
# ./type-command
type-command: the variable TYPE_CMD_ENABLED is not set, set it to 'no' to surpress this message; set the TYPE_CMD_TYPE for the command to type

Example: export TYPE_CMD_ENABLED=yes; export TYPE_CMD_TYPE=date
  • Export the variable to controls if the program should try to type a command or not
# export TYPE_CMD_ENABLED=yes
# ./type-command
#
  • Specify the command that you wish to be typed
# export TYPE_CMD_ENABLED=yes; export TYPE_CMD_TYPE=date
# ./type-command
# date
Sun Mar 30 19:27:55 UTC 2014>

References

http://stackoverflow.com/questions/10866005/bash-how-to-prefill-command-line-input
http://stackoverflow.com/questions/11198603/inject-keystroke-to-different-process-using-bash
http://unix.stackexchange.com/questions/48103/construct-a-command-by-putting-a-string-into-a-tty

http://fossies.org/linux/misc/old/console-tools-0.3.3.tar.gz%3at/console-tools-0.3.3/vttools/writevt.c

http://man7.org/linux/man-pages/man4/tty_ioctl.4.html
http://man7.org/linux/man-pages/man3/tcflush.3.html
http://www.tldp.org/LDP/lpg/node143.html

No comments:

Post a Comment