HORIZON HASKELLDocslts/ghc-9.10.x248f8f02026-10-05Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · 248f8f0 · 2026-10-05

Moduleshelly-1.12.1Haskell2010

Shelly

A module for shell-like programming in Haskell. Shelly's focus is entirely on ease of use for those coming from shell scripting. However, it also tries to use modern libraries and techniques to keep things efficient.

The functionality provided by this module is (unlike standard Haskell filesystem functionality) thread-safe: each Sh maintains its own environment and its own working directory.

Recommended usage includes putting the following at the top of your program, otherwise you will likely need either type annotations or type conversions

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ExtendedDefaultRules #-}
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
import Shelly
import qualified Data.Text as T
default (T.Text)
  • 12 types
  • 2 classes
  • 131 values
  • Packageshelly-1.12.1
  • Exports146
  • LanguageHaskell2010
  • LicenceBSD-3-Clause
  • SourceShelly.hs

Entering Sh

19 declarations
newtypenewtype Sh a
#
Instances17Monad, Functor, MonadFail, Applicative, MonadIO, MonadCatch, …
typetype ShIO a = Sh a
#

Deprecated. Use Sh instead of ShIO

ShIO is Deprecated in favor of Sh, which is easier to type.

valueshelly :: MonadIO m => Sh a -> m a
#

Enter a Sh from (Monad)IO. The environment and working directories are inherited from the current process-wide values. Any subsequent changes in processwide working directory or environment are not reflected in the running Sh.

valueshellyNoDir :: MonadIO m => Sh a -> m a
#

Deprecated. Just use shelly. The default settings have changed

Deprecated now, just use shelly, whose default has been changed. Using this entry point does not create a .shelly directory in the case of failure. Instead it logs directly into the standard error stream (stderr).

valueshellyFailDir :: MonadIO m => Sh a -> m a
#

Using this entry point creates a .shelly directory in the case of failure where errors are recorded.

valueasyncSh :: Sh a -> Sh (Async a)
#

Spawn an asynchronous action with a copy of the current state.

valuesub :: Sh a -> Sh a
#

Enter a sub-Sh that inherits the environment The original state will be restored when the sub-Sh completes. Exceptions are propagated normally.

valuesilently :: Sh a -> Sh a
#

Create a sub-Sh in which external command outputs are not echoed and commands are not printed. See sub.

valueverbosely :: Sh a -> Sh a
#

Create a sub-Sh in which external command outputs are echoed and Executed commands are printed See sub.

valueescaping :: Bool -> Sh a -> Sh a
#

Create a sub-Sh with shell character escaping on or off. Defaults to True.

Setting to False allows for shell wildcard such as * to be expanded by the shell along with any other special shell characters. As a side-effect, setting to False causes changes to PATH to be ignored: see the run documentation.

valueprint_stdout :: Bool -> Sh a -> Sh a
#

Create a sub-Sh with stdout printing on or off Defaults to True.

valueprint_stderr :: Bool -> Sh a -> Sh a
#

Create a sub-Sh with stderr printing on or off Defaults to True.

valueonCommandHandles :: StdInit -> Sh a -> Sh a
#

When running an external command, apply the given initializers to the specified handles for that command. This can for example be used to change the encoding of the handles or set them into binary mode.

valuetracing :: Bool -> Sh a -> Sh a
#

Create a sub-Sh where commands are not traced Defaults to True. You should only set to False temporarily for very specific reasons.

valueerrExit :: Bool -> Sh a -> Sh a
#

named after bash -e errexit. Defaults to True. When True, throw an exception on a non-zero exit code. When False, ignore a non-zero exit code. Not recommended to set to False unless you are specifically checking the error code with lastExitCode.

valuelog_stdout_with :: (Text -> IO ()) -> Sh a -> Sh a
#

Create a sub-Sh in which stdout is sent to the user-defined logger. When running with silently the given log will not be called for any output. Likewise the log will also not be called for output from run_ and bash_ commands.

valuelog_stderr_with :: (Text -> IO ()) -> Sh a -> Sh a
#

Create a sub-Sh in which stderr is sent to the user-defined logger. When running with silently the given log will not be called for any output. However, unlike log_stdout_with the log will be called for output from run_ and bash_ commands.

Running external commands

25 declarations
valuerun :: FilePath -> [Text] -> Sh Text
#

Execute an external command. Takes the command name and arguments.

You may prefer using cmd instead, which is a variadic argument version of this function.

stdout and stderr are collected. The stdout is returned as a result of run, and complete stderr output is available after the fact using lastStderr. If the output does not end with a newline, it is automatically added.

All of the stdout output will be loaded into memory. You can avoid this if you don't need stdout by using run_, If you want to avoid the memory and need to process the output then use runFoldLines or runHandle or runHandles.

By default shell characters are escaped and the command name is a name of a program that can be found via PATH. Shelly will look through the PATH itself to find the command.

When escaping is set to False, shell characters are allowed. Since there is no longer a guarantee that a single program name is given, Shelly cannot look in the PATH for it. a PATH modified by setenv is not taken into account when finding the exe name. Instead the original Haskell program PATH is used. On a Posix system the env command can be used to make the setenv PATH used when escaping is set to False. env echo hello instead of echo hello.

valuerun_ :: FilePath -> [Text] -> Sh ()
#

The same as run, but return () instead of the stdout content. The stdout will be read and discarded line-by-line.

valuecmd :: ShellCmd result => FilePath -> result
#

Variadic argument version of run. Please see the documenation for run.

The syntax is more convenient, but more importantly it also allows the use of a FilePath as a command argument. So an argument can be a Text or a FilePath without manual conversions. a FilePath is automatically converted to Text with toTextIgnore.

Convenient usage of cmd requires the following:

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ExtendedDefaultRules #-}
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
import Shelly
import qualified Data.Text as T
default (T.Text)
value(-|-) :: Sh Text -> Sh b -> Sh b
#

Pipe operator. Set the stdout the first command as the stdin of the second. This does not create a shell-level pipe, but hopefully it will in the future. To create a shell level pipe you can set escaping False and use a pipe | character in a command.

valuelastExitCode :: Sh Int
#

The exit code from the last command. Unless you set errExit to False you won't get a chance to use this: a non-zero exit code will throw an exception.

valuecommand :: FilePath -> [Text] -> [Text] -> Sh Text
#

Bind some arguments to run for re-use. Example:

monit = command "monit" ["-c", "monitrc"]
monit ["stop", "program"]
valuecommand_ :: FilePath -> [Text] -> [Text] -> Sh ()
#

Bind some arguments to run_ for re-use. Example:

monit_ = command_ "monit" ["-c", "monitrc"]
monit_ ["stop", "program"]
valuecommand1 :: FilePath -> [Text] -> Text -> [Text] -> Sh Text
#

Bind some arguments to run for re-use, and require 1 argument. Example:

git = command1 "git" []
git "pull" ["origin", "master"]
valuecommand1_ :: FilePath -> [Text] -> Text -> [Text] -> Sh ()
#

Bind some arguments to run_ for re-use, and require 1 argument. Example:

git_ = command1_ "git" []
git "pull" ["origin", "master"]
valuesshPairs :: Text -> [(FilePath, [Text])] -> Sh Text
#

Run commands over SSH. An ssh executable is expected in your path. Commands are in the same form as run, but given as pairs

sshPairs "server-name" [("cd", "dir"), ("rm",["-r","dir2"])]

This interface is crude, but it works for now.

Please note this sets escaping to False, and the remote commands are quoted with single quotes, in a way such that the remote commands will see the literal values you passed, this means that no variable expansion and alike will done on either the local shell or the remote shell, and that if there are a single or double quotes in your arguments, they need not to be quoted manually.

Internally the list of commands are combined with the string && before given to ssh.

classclass ShellCmd t where
#

For the variadic function cmd.

Partially applied variadic functions require type signatures.

Methods

Instances6ShellCmd
classclass CmdArg a where
#

Argument converter for the variadic argument version of run called cmd. Useful for a type signature of a function that uses cmd.

Methods

Instances3CmdArg

Running commands Using handles

6 declarations
valuerunHandles
  1. :: FilePath

    Command.

  2. -> [Text]

    Arguments.

  3. -> [StdHandle]

    Optionally connect process i/o handles to existing handles.

  4. -> (Handle -> Handle -> Handle -> Sh a)

    stdin, stdout and stderr.

  5. -> Sh a
#

Similar to run but gives direct access to all input and output handles.

Be careful when using the optional input handles. If you specify Inherit for a handle then attempting to access the handle in your callback is an error.

valuetransferLinesAndCombine :: Handle -> (Text -> IO ()) -> IO Text
#

Transfer from one handle to another For example, send contents of a process output to stdout. Does not close the write handle.

Also, return the complete contents being streamed line by line.

valuetransferFoldHandleLines
  1. :: a
  2. -> FoldCallback a
  3. -> Handle
  4. -> Text -> IO ()
  5. -> IO a
#

Transfer from one handle to another For example, send contents of a process output to stdout. Does not close the write handle.

Also, fold over the contents being streamed line by line.

datadata StdStream
#

Constructors

  • Inherit

    Inherit Handle from parent

  • UseHandle Handle

    Use the supplied Handle

  • CreatePipe

    Create a new pipe. The returned Handle will use the default encoding and newline translation mode (just like Handles created by openFile).

  • NoStream

    Close the stream's file descriptor without passing a Handle. On POSIX systems this may lead to strange behavior in the child process because attempting to read or write after the file has been closed throws an error. This should only be used with child processes that don't use the file descriptor at all. If you wish to ignore the child process's output you should either create a pipe and drain it manually or pass a Handle that writes to /dev/null.

Instances2Eq, Show
  • Eq StdStreamDefined in process-1.6.26.1 · System.Process.Common
  • Show StdStreamDefined in process-1.6.26.1 · System.Process.Common

Handle manipulation

4 declarations

Modifying and querying environment

9 declarations
valuesetenv :: Text -> Text -> Sh ()
#

Set an environment variable. The environment is maintained in Sh internally, and is passed to any external commands to be executed.

valueget_env_text :: Text -> Sh Text
#

Fetch the current value of an environment variable. Both empty and non-existent variables give empty string as a result.

valueget_env_def :: Text -> Text -> Sh Text
#

Deprecated. use fromMaybe DEFAULT get_env

Fetch the current value of an environment variable. Both empty and non-existent variables give the default Text value as a result.

valueprependToPath :: FilePath -> Sh ()
#

Prepend the filepath to the PATH env variable. Similar to appendToPath but gives high priority to the filepath instead of low priority.

Environment directory

4 declarations
valuecd :: FilePath -> Sh ()
#

Change current working directory of Sh. This does not change the working directory of the process we are running it. Instead, Sh keeps track of its own working directory and builds absolute paths internally instead of passing down relative paths.

valuechdir :: FilePath -> Sh a -> Sh a
#

cd, execute a Sh action in the new directory and then pop back to the original directory.

Printing

10 declarations
valueecho :: Text -> Sh ()
#

Echo text to standard (error, when using _err variants) output. The _n variants do not print a final newline.

valueecho_n :: Text -> Sh ()
#

Echo text to standard (error, when using _err variants) output. The _n variants do not print a final newline.

valueecho_err :: Text -> Sh ()
#

Echo text to standard (error, when using _err variants) output. The _n variants do not print a final newline.

valueecho_n_err :: Text -> Sh ()
#

Echo text to standard (error, when using _err variants) output. The _n variants do not print a final newline.

valuetag :: Sh a -> Text -> Sh a
#

Same as trace, but for use in combinator style: action tag message.

valuetrace :: Text -> Sh ()
#

Internally log what occurred. Log will be re-played on failure.

Querying filesystem

8 declarations
valuels :: FilePath -> Sh [FilePath]
#

List directory contents. Does not include . and .., but it does include (other) hidden files.

valuewhich :: FilePath -> Sh (Maybe FilePath)
#

Get a full path to an executable by looking at the PATH environement variable. Windows normally looks in additional places besides the PATH: this does not duplicate that behavior.

Filename helpers

9 declarations
valueabsPath :: FilePath -> Sh FilePath
#

Make a relative path absolute by combining with the working directory. An absolute path is returned as is. To create a relative path, use relPath.

value(</>)
  1. :: (ToFilePath filepath1, ToFilePath filepath2)
  2. => filepath1
  3. -> filepath2
  4. -> FilePath
#

Uses System.FilePath, but can automatically convert a Text.

valuerelPath :: FilePath -> Sh FilePath
#

Makes a relative path relative to the current Sh working directory. An absolute path is returned as is. To create an absolute path, use absPath.

valuerelativeTo
  1. :: FilePath

    Anchor path, the prefix.

  2. -> FilePath

    Make this relative to anchor path.

  3. -> Sh FilePath
#

Make the second path relative to the first. Will canonicalize the paths if necessary.

Manipulating filesystem

9 declarations
valuemv :: FilePath -> FilePath -> Sh ()
#

Move a file. The second path could be a directory, in which case the original file is moved into that directory. wraps directory renameFile, which may not work across FS boundaries

valuerm :: FilePath -> Sh ()
#

Remove a file. Does fail if the file does not exist (use rm_f instead) or is not a file.

valuerm_f :: FilePath -> Sh ()
#

Remove a file. Does not fail if the file does not exist. Does fail if the file is not a file.

valuerm_rf :: FilePath -> Sh ()
#

A swiss army cannon for removing things. Actually this goes farther than a normal rm -rf, as it will circumvent permission problems for the files we own. Use carefully. Uses removeDirectoryRecursive

valuecp :: FilePath -> FilePath -> Sh ()
#

Copy a file. The second path could be a directory, in which case the original file name is used, in that directory.

valuemkdir :: FilePath -> Sh ()
#

Create a new directory (fails if the directory exists).

valuemkdir_p :: FilePath -> Sh ()
#

Create a new directory, including parents (succeeds if the directory already exists).

valuemkdirTree :: Tree FilePath -> Sh ()
#

Create a new directory tree. You can describe a bunch of directories as a tree and this function will create all subdirectories. An example:

exec = mkTree $
          "package" # [
               "src" # [
                   "Data" # leaves ["Tree", "List", "Set", "Map"]
               ],
               "test" # leaves ["QuickCheck", "HUnit"],
               "dist/doc/html" # []
           ]
        where (#) = Node
              leaves = map (# [])

reading/writing Files

7 declarations
valuetouchfile :: FilePath -> Sh ()
#

Update a file, creating (a blank file) if it does not exist.

valuewithTmpDir :: (FilePath -> Sh a) -> Sh a
#

Create a temporary directory and pass it as a parameter to a Sh computation. The directory is nuked afterwards.

exiting the program

4 declarations
valueexit :: Int -> Sh a
#

exit 0 means no errors, all other codes are error conditions.

valuequietExit :: Int -> Sh a
#

For exiting with status > 0 without printing debug information.

Exceptions

11 declarations

convert between Text and FilePath

3 declarations

Utility Functions

4 declarations
valuewhenM :: Monad m => m Bool -> m () -> m ()
#

A monadic-conditional version of the when guard.

valuetime :: Sh a -> Sh (Double, a)
#

Run a Sh computation and collect timing information. The value returned is the amount of *real* time spent running the computation in seconds, as measured by the system clock. The precision is determined by the resolution of getCurrentTime.

Re-exported for your convenience

5 declarations
methodliftIO :: IO a -> m a
#

Lift a computation from the IO monad. This allows us to run IO computations in any monadic stack, so long as it supports these kinds of operations (i.e. IO is the base monad for the stack).

Example
import Control.Monad.Trans.State -- from the "transformers" library

printState :: Show s => StateT s IO ()
printState = do
  state <- get
  liftIO $ print state

Had we omitted liftIO, we would have ended up with this error:

• Couldn't match type ‘IO’ with ‘StateT s IO’
 Expected type: StateT s IO ()
   Actual type: IO ()

The important part here is the mismatch between StateT s IO () and IO ().

Luckily, we know of a function that takes an IO a and returns an (m a): liftIO, enabling us to run the program and see the expected results:

> evalStateT printState "hello"
"hello"

> evalStateT printState 3
3
valuewhen :: Applicative f => Bool -> f () -> f ()
#

Conditional execution of Applicative expressions. For example,

Examples
when debug (putStrLn "Debugging")

will output the string Debugging if the Boolean value debug is True, and otherwise do nothing.

Example1 expression
putStr "pi:" >> when False (print 3.14159)pi:
valueunless :: Applicative f => Bool -> f () -> f ()
#

The reverse of when.

Examples
Example1 expression
do x <- getLine       unless (x == "hi") (putStrLn "hi!")comingupwithexamplesisdifficulthi!
Example1 expression
unless (pi > exp 1) NothingJust ()
typetype FilePath = String
#

File and directory names are values of type String, whose precise meaning is operating system dependent. Files can be opened, yielding a handle which can then be used to operate on the contents of that file.

Instances1ToFilePath
  • ToFilePath FilePathDefined in shelly-1.12.1 · Shelly
value(<$>) :: Functor f => (a -> b) -> f a -> f b
#

An infix synonym for fmap.

The name of this operator is an allusion to $. Note the similarities between their types:

 ($)  ::              (a -> b) ->   a ->   b
(<$>) :: Functor f => (a -> b) -> f a -> f b

Whereas $ is function application, <$> is function application lifted over a Functor.

Examples

Convert from a Maybe Int to a Maybe String using show:

Example1 expression
show <$> NothingNothing
Example1 expression
show <$> Just 3Just "3"

Convert from an Either Int Int to an Either Int String using show:

Example1 expression
show <$> Left 17Left 17
Example1 expression
show <$> Right 17Right "17"

Double each element of a list:

Example1 expression
(*2) <$> [1,2,3][2,4,6]

Apply even to the second element of a pair:

Example1 expression
even <$> (2,2)(2,True)

internal functions for writing extensions

2 declarations
valueput :: State -> Sh ()
#

find functions

7 declarations
valuefind :: FilePath -> Sh [FilePath]
#

List directory recursively (like the POSIX utility "find"). listing is relative if the path given is relative. If you want to filter out some results or fold over them you can do that with the returned files. A more efficient approach is to use one of the other find functions.