0

If I write a Scala script (or App) that just prints out the command line arguments, I notice that it ignores all the '!' characters. For example, if my script looks like:

println(args(0))

And I run it with:

scala MyScript "Hello!"

I get the output:

Hello

And if I run it with:

scala MyScript "Hello! World!"

I also get:

Hello

What's going on? What is the purpose of the ! character in arguments that causes this behaviour?

emote_control
  • 745
  • 6
  • 21
  • 4
    I'm guessing that the `!` character is being interpreted specially by your shell and this has nothing to do with Scala. – Chris Martin Mar 06 '15 at 03:26
  • Which shell are you using? What is the result of using single quotes? `scala MyScript 'Hello! World!'`? – Nader Ghanbari Mar 06 '15 at 03:34
  • I'm running it from the Windows command line. It's not the shell. I've done the exact same script in Java, and Java reads the ! characters just fine. If I enclose it in single quotes, like `'Hello World!'` I get `'Hello` and `World'`. – emote_control Mar 06 '15 at 14:18
  • Interestingly, if I write `scala MyScript "Hello! World! Hi!"` the output is `Hello Hi`, which suggests that scala interprets the `!` character as some kind of delimiter indicating a section of the parameters to ignore. That suggests that there should be some kind of escape character, but I haven't been able to figure out what, or find it anywhere. – emote_control Mar 06 '15 at 14:47

1 Answers1

2

! is history substitution.

Try scala MyScript hello! with ! at EOL to see it work as if quoted.

http://www.gnu.org/software/bash/manual/bashref.html#Event-Designators

http://www.gnu.org/software/bash/manual/bashref.html#Single-Quotes

On windows, the "scala.bat" command script has delayed expansion enabled.

http://en.wikibooks.org/wiki/Windows_Batch_Scripting

http://en.wikibooks.org/wiki/Windows_Batch_Scripting#SETLOCAL

http://en.wikibooks.org/wiki/Windows_Batch_Scripting#Command-line_arguments

To disable interpretation of !myvar!:

C:\Users\you> scala greeting.script "hello^!"
hello!

C:\Users\you> set world= Bob

C:\Users\you> scala greeting.script "hello!world!"
hello Bob
som-snytt
  • 39,429
  • 2
  • 47
  • 129
  • I'm working in Windows command line, and when I run an equivalent Java program it picks up the ! character. It appears to be specific to Scala. – emote_control Mar 06 '15 at 14:23
  • Delayed expansion doesn't explain why the same parameters work for Java programs, but it's the best answer I've seen so far. Have an upvote. – emote_control Mar 06 '15 at 17:02
  • Have a jira issue. https://issues.scala-lang.org/browse/SI-9204 I also clarified the answer here. – som-snytt Mar 06 '15 at 22:06
  • That's great. I'll keep an eye on the issue status, but thanks for the workaround, too. – emote_control Mar 09 '15 at 14:11