How to execute system commands?

Clojure

Clojure Problem Overview


How can I execute system specific commands and get their response in Clojure? For example, let's assume we're on a Linux machine, how can I call top or free, and get their results for further processing?

Clojure Solutions


Solution 1 - Clojure

(use '[clojure.java.shell :only [sh]])
(sh "free")
(sh "top" "-bn1")

See also: http://clojuredocs.org/clojure_core/clojure.java.shell/sh

Solution 2 - Clojure

You should be able to use the Java Runtime.exec method as follows:

(import 'java.lang.Runtime)

(. (Runtime/getRuntime) exec "your-command-line-here")

The Runtime.exec method returns a Process object that you can query to get the standard output etc. as needed.

Solution 3 - Clojure

If you are willing to get a little higher in term of abstractions (although no that high), I would recommend Conch, as I found it to make very readable code.

Solution 4 - Clojure

You could use the babashka library to run shell commands in Clojure. An example would be

#!/usr/bin/env bb
(require '[clojure.java.shell :refer [sh]])
(sh "top")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsjacView Question on Stackoverflow
Solution 1 - ClojureoverthinkView Answer on Stackoverflow
Solution 2 - ClojuremikeraView Answer on Stackoverflow
Solution 3 - ClojurenhaView Answer on Stackoverflow
Solution 4 - ClojureCambodianCoderView Answer on Stackoverflow