20090522 making scripts interactive - plembo/onemoretech GitHub Wiki

title: making scripts interactive link: https://onemoretech.wordpress.com/2009/05/22/making-scripts-interactive/ author: lembobro description: post_id: 319 created: 2009/05/22 05:21:48 created_gmt: 2009/05/22 05:21:48 comment_status: open post_name: making-scripts-interactive status: publish post_type: post

making scripts interactive

Most of my scripting involves automated processes that get kicked off by cron, recently I had to modify some little utilities I’d written so they could be used more easily by other admins.

Making a script interactive is pretty easy. This brief article will cover how to get input from the user that will be used as variables by the process.

`

#! /usr/bin/perl
use strict;
	
print "n";
print "Script to do something with input from the usern":
print "n";
print "Target E-Business database SID: ";
my $hostname = <STDIN>;
chomp($hostname);
print "Target APPS password: ";
my $password = <STDIN>;
chomp($password);
print "n";
	
[do stuff with variables here]

`

Two things about this sample code. First, you’ll notice I “chomp” the variable once a value has been assigned to it with the user’s input (which is taken from the default filehandle for standard input, <STDIN>). That’s to strip off the newline that gets sent after the user types in their response and hits the return key (er… “enter” key, yes I am dating myself on that one).

Second, the way this is currently written, everything that gets typed by the user is echoed on screen, including the requested password value. Because that might make some people uncomfortable, here’s a way to turn echoing off and back on again:

`

#! /usr/bin/perl
use strict;
use Term::ReadKey;
	
print "n";
print "Script to do something with input from the usern":
print "n";
print "Target E-Business database SID: ";
my $hostname = ;
chomp($hostname);
print “Target APPS password: “;
ReadMode(’noecho’);
my $password = ;
ReadMode(’restore’);
chomp($password);
print “n”;
	
[do stuff with variables here]

`

The ReadMode method in Term::ReadKey lets you toggle echoing off and back on again with either a friendly label (’noecho’ or ‘restore’) or a numeric value (2 for ‘noecho’ and 0 for ‘restore’). This little tip was courtesy of perlfaq8, which can be accessed by doing a “perldoc perlfaq8”. If you wanted to just pull back the discussion of passwords, you can issue “perldoc -q passwords” and the system will retrieve it for you.

Copyright 2004-2019 Phil Lembo

⚠️ **GitHub.com Fallback** ⚠️