1

I've been messing around with .cmd scripts, and wanted to practice piping. I wrote one script to make files, and another to edit them with Notepad++. The making script (called create.cmd) is as follows:

@echo off
copy nul %1 > nul
echo %1

And the edit script (called edit.cmd) is as follows:

@echo off
start notepad++.exe %1

Now, I wanted to try and make a file, and then pipe its output (hence the echo line) in the form of the name of the file to the edit script. So what I wrote was this:

create foo.txt | edit

However, this fails - I get an open Notepad++ window, but my newly-created file does not appear there. What am I missing or doing wrong here?

Koz Ross
  • 3,040
  • 2
  • 24
  • 44

2 Answers2

1

You are not reading from the pipe in your second batch file.

For reading just one line of output from the first batch, the filename, this should suffice:

@echo off
set /p file=
start notepad.exe %file%

Otherwise check Read stdin stream in a batch file for reading multi-lined input.

Community
  • 1
  • 1
mockinterface
  • 14,452
  • 5
  • 28
  • 49
  • Thank you very much! Solved it perfectly. Out of interest, what does that /p do for the variable declared by set in your script? – Koz Ross Feb 01 '14 at 04:15
  • The `/p` switch tells `set` to set a variable to a line read from the standard input. Type `help set` in the prompt, it is documented there. – mockinterface Feb 01 '14 at 04:25
  • Thanks for that. However, I find a script with this solution no longer takes a normal argument! For example, if I try something like `edit foo.txt`, it asks for the input a second time! Is there any way I can default to a 'normal' argument if I'm not piping, and your solution if I am? – Koz Ross Feb 01 '14 at 11:31
  • I suggest that you submit this as a new question. Nevertheless, on unix it is common to have the `-` argument indicate stdin. So you would say `tar foo.txt` or `tar -` and the tar command would know that in the second case it needs to read from the stdin instead of a file. You can check %1 and then decide to whether `set /p` or treat it as a file. – mockinterface Feb 01 '14 at 11:39
0

edit.bat has no %1 parameter

You could try this:

@echo off
copy nul %1 > nul
echo %1
call edit %1
foxidrive
  • 40,353
  • 10
  • 53
  • 68