Search code examples
clojure

How To Execute A Split String As Arguments To Clojure.shell/sh


I have a command like:

(clojure.java.shell/sh "curl" "https://somesite.com" "-F" "[email protected]")

and I want to create a function that will run standard shell commands I supply... something like this:

(defn run-shell-command [command]
  (clojure.java.shell/sh (clojure.string/split command #" ")))

so that I could call it like this:

(run-shell-command "curl https://somesite.com -F [email protected]")

but this throws:

Unhandled java.lang.IllegalArgumentException
   No value supplied for key: ["curl" "https://somesite.com" "-F" "[email protected]"]

How do I make this work?

(of course, open to better ideas for how to do this)


Solution

  • Your question is a common one amongst beginner lispers: If we have a function accepting arguments, how can we apply the function on a list of these arguments?

    (defn f [a b c] (+ a b c))
    
    (def args [1 2 3])
    

    The answer is, as hinted above, the apply method. The method applies a function to a list of arguments. So in the example above:

    (= (f 1 2 3)
       (apply f args))
    

    i.e

    (defn run-shell-command [command]
      (apply clojure.java.shell/sh (clojure.string/split command #" ")))