Sys.argv() and "\n"

Hi,

I am trying to use the command line to input using Sys.argv, and the newline character seems to be interpreted as a literal instead of a new line.

Example:

let () = print_endline Sys.argv.(1)

And I try to execute using

./main.exe “something\n”

Then on printing, it prints the “something\n”, instead of using “\n” to go to the next line. How do fix this?

Thanks,
Gokul

The problem is in the invocation - the shell doesn’t understand the “\n” in a string cf.,

dra@thor:~$ echo "something\n"
something\n

For the echo command, you may be able to add -e to achieve this:

dra@thor:~$ echo -e "something\n"
something

For passing a literal newline to something, it depends on the shell. In bash, you can do this with ANSI C-quoting:

dra@thor:~$ echo $'something\n'
something

5 Likes

Thanks, yes this works, I was using bash.

I feel like it’s relevant to note that expecting useful preservation of whitespace, newlines, etc, in shells and shell-based manipulation, is fraught with problems. I mean, sure if you work hard at it, you can usually make it work. But it’s not worth the candle. Better to just assume whitespace is not preserved varbatim. Ditto with the many different kinds of quotation-marks – it’s just cruising for a bruising.

2 Likes