Read a user string from the console with gawk
I was often asked how a user can enter some text (and not only a key) into a batch script.
As usual let's call gawk at the rescue! The following command will prompt the
user to enter a string and print it immediately:
gawk.exe "BEGIN { getline; print \"User string: \"$0; }"
Let's try it in a Command prompt:
Now we are able to ask the user to enter a string from the console,
but how to inject the result in the caller batch script? First let's use
the following command:
gawk.exe "BEGIN { getline; print \"set myvar=\"$0; }"
and the output:
Great, but %myvar% is still not available from the caller
batch script! So we will now export the result into a temp batch file
and call this temp batch file immediately after. Let's take a look at
the following script:
rem ---------- Ask user to enter a string
rem Params: %1 Text message
rem Return: User text string in %ret%
:_getuserstring
set ret=
if {%1}=={} (goto :EOF)
echo %1
gawk.exe "BEGIN { getline; print \"set ret=\"$0; }" > $$$0.cmd
if exist $$$0.cmd ((call $$$0.cmd) & (del $$$0.cmd))
goto :EOF
I've defined a batch routine called _getuserstring. This
routine must be called with one parameter (a line of text
describing what is asked from the user), if this parameter is omitted
the routine will exit. If not the line of text is printed out and the
user prompted to enter his string. Then the result is exported to a
local temp batch script and if it exists, it is called immediately and deleted. We can now access the user string using the
%ret% variable directly from the caller batch.
Let's take a look to the following batch script called hello.cmd:
@echo off
rem ---------- Main batch script
call :_getuserstring "What's your name?"
if defined ret ((echo.) & (echo Hello %ret%!))
goto :end
rem ---------- Ask user to enter a string
rem Params: %1 Text message
rem Return: User text string in %ret%
:_getuserstring
set ret=
if {%1}=={} (goto :EOF)
echo %1
gawk.exe "BEGIN { getline; print \"set ret=\"$0; }" > $$$0.cmd
if exist $$$0.cmd ((call $$$0.cmd) & (del $$$0.cmd))
goto :EOF
:end
and the result:
That's it! We can now ask a string from the user in a batch script!
I know there are also other scripting methods to do that, it's just
another example of what gawk can do for you.
If your script will only run under Windows 2000 or more, you
can also use the "SET /P variable=[promptString]" command. The /P switch allows you to set the value of a variable to a line of input
entered by the user. Displays the specified promptString before reading
the line of input. The promptString can be empty. This won't work under
Windows 9x/Me and NT. In that case you can still use the gawk method...
|