Piping from terminal into D program
Brian Tiffin
btiffin at gnu.org
Sat Sep 4 16:57:40 UTC 2021
On Saturday, 4 September 2021 at 15:41:51 UTC, eXodiquas wrote:
> Hello everyone,
>
> I created a small little D program that reads in a string from
> the command line and shuffles the letters of the nouns a bit
> around. This is pretty straight forward, but what I see now
> happening is a bit strange, at least for me.
>
> I am reading the args out of the main function arguments.
>
> ```d
> void main(string[] args) {
> args.writeln();
> }
> ```
>
> this works fine whenever I call the program like
> `./nounscramble "Hello, my name is Earl!"` the string shows up
> in `args[1]`. But when I call `echo "Hello, my name is Earl!" |
> ./nounscramble` it does not show up in the args array, the only
> thing showing up is the name of the executable (which is
> expected).
>
> My question is now, can someone explain what I am doing wrong?
> Maybe I misunderstood the pipe in Linux systems and it is
> obvious for someone who knows how this works exactly, or maybe
> D works differently with pipes and I havn't found the correct
> documentation.
>
> Thanks in advance. :)
>
> eXodiquas
There are two things happening here. Command line arguments and
stdin, standard in.
When part of an actual command line, parameters are expanded as
command line arguments, passed to the `main` function. When
`echo`ed, the arguments are passed to the `echo` command, which
then displays those arguments on stdout, standard out. A pipe is
connecting the stdout of the left hand side, and streaming that
data to the stdin of the right hand side, after the pipe symbol.
These are not command line arguments, but data on the
stdin/stdout channels (file descriptors to be more exact with the
jargon).
You could write is as `echo thing | ./nounscramble commandarg`.
`echo` will display *thing*. Your program with get `commandarg`
in the array passed to `main`, but the stdout data displayed by
`echo` is never read, and just ends up in a pipeline bitbucket at
the end of processing.
Most shells, like `bash` allow a different kind of parameter
replacement, command arg expansion. Use like `./nounstatement
$(echo this that)`, and the shell will manipulate things to
replace the stdout from the `echo` into word expanded arguments
placed in the atring array used by `main`.
Cheers
More information about the Digitalmars-d-learn
mailing list