I discussed why this doesn't work when you use the Java Process and ProcessBuilder classes many years ago, but in short, the problem is that you're trying to execute a pipeline, and a pipe is a shell construct, and you don't have a shell. Scala> val result = "ls -al | grep Foo" ! However, as you'll see in the REPL, this won't work: When you want to run external system commands in a pipeline, your first instinct will be to try to run them like this: In Scala you do that with the "!!" operator:Īs you can see in this example, result is now a normal Scala String, and you can operate on it as desired. While it's often nice to be able to execute system commands and get access to the status code of the command, you'll often want to be able to execute a command and get the output from that command. If you're familiar with programming Unix shell scripts, you know that a return code of zero is good (it means "success"), while any other value means there was a problem. We can demonstrate that by assigning this command to a variable, and then printing that variable. If you're familiar with Scala and the REPL environment, you can see that this command returns a result of zero (0). (If you're not familiar with the Unix "ls -al" command, it shows a list of files and directories in the current directory.) You just need one import statement, and then you run your command as shown below with the "!" operator:ĭrwxr-xr-x 10 Al staff 340 May 18 18:00. It's very easy to run external system commands in Scala. Executing system commands and getting their status code (exit code) The operators Scala makes available are much more like Perl or Ruby, and the operators themselves are consistent with traditional shell commands, and are therefore easy to remember. When it comes to executing external system commands, Scala is a dramatic improvement over Java. Scala exec FAQ: How do I execute external system commands in Scala?
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |