1

I'd like to compile a bash script from within Scala. To ease this I'd like to use string interpolation. However bash variables and Scala string interpolation don't seem to play well with each other. Here's an example

val someFile="test.txt"

val bashScript = s"""
newFile=${someFile}.filtered
grep foobar $someFile > $newFile
"""

This will result in a compile error because $newFile can not be interpolated. However, literally keeping $newFile as it is would give the expected valid bash script.

Possible solutions have crossed my mind, but I don't know if they are feasible nor how to implement them

  1. Tell scala to use a different prefix for the interpolated expression, e.g. by implementing a custom interpolator

  2. Somehow ignore non-interpolatable expressions and keep them as they are.

1

2 Answers 2

3

The escape character for string interpolation is $, so

val someFile="test.txt"

val bashScript = s"""
newFile=${someFile}.filtered
grep foobar $someFile > $$newFile
"""

should do what you want.

Sign up to request clarification or add additional context in comments.

Comments

1

You can escape the dollar sign by adding a second dollar sign. So the following should work.

val someFile="test.txt"

val bashScript = s"""
  newFile=${someFile}.filtered
  grep foobar $someFile > $$newFile
"""

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.