Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In batch, how do I create spaces at the beginning of a input prompt string?

Tags:

batch-file

cmd

Let's say I have a batch file that has "padding" in it, and I want to indent the beginning of the prompt string for the user to type in. If I use spaces, it will not show up when run, it just ignores the spaces. This script for an example:

@echo off

echo.
echo.
echo    Hi.
echo    Please input something.
echo.
set /P input=   

After the = there is three spaces, and what I expect is that the marker for input is away from the edge of the command box, however these spaces are ignored.

How can I fix this problem? I am using Windows 7 SP1.

like image 580
Markum Avatar asked Mar 25 '12 22:03

Markum


People also ask

How do you add a space in a batch file?

To create a blank line in a batch file, add an open bracket or period immediately after the echo command with no space, as shown below. Adding @echo off at the beginning of the batch file turns off the echo and does not show each of the commands.

How do I use spaces in the command prompt?

Sometimes: Use the Caret Character to Escape Spaces ( ^ ) In the Command Prompt, the caret character ( ^ ) will let you escape spaces—in theory. Just add it before each space in the file name. (You'll find this character in the number row on your keyboard.

What does %% do in batch?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

Can a batch file prompt for input?

You are able to prompt a user for input using a Batch script function.


2 Answers

You need to add a dot after the echo The following example will output "Test" with three leading spaces:

echo.   Test

Same works for tabulator. The following example will output "Test" with one leading tab:

echo.   Test
like image 119
Frank Menzel Avatar answered Oct 19 '22 19:10

Frank Menzel


As the comments above state, Vista and beyond strip leading spaces in a SET /P prompt.

The way to get around the problem is to define and use a backspace character in the prompt.

::define a variable containing a single backspace character
for /f %%A in ('"prompt $H &echo on &for %%B in (1) do rem"') do set BS=%%A

set /p var=%BS%   Leading spaces will not show properly.

Normally the prompt will be at the beginning of a line, so the above works just fine.

But if the prompt is issued from the middle of a line (very unusual), then a leading character should be included prior to the <BS>, since the backspace will erase whatever was before it.

<nul set/p=Leave the cursor at the end of this line:
set /p var=.%BS%   The dot (any char) is necessary to prevent the <BS> from erasing the :
like image 40
dbenham Avatar answered Oct 19 '22 20:10

dbenham