Print exactly one line to stdout
To print more than one line see printf, which also supports formatted output
:: a typeCtrl KGHC 9.10.3 · lts/ghc-9.10.x · c74966e · 2026-09-27
Moduleturtle-1.6.2Haskell2010
This module provides a large suite of utilities that resemble Unix utilities.
Many of these commands are just existing Haskell commands renamed to match their Unix counterparts:
:set -XOverloadedStringscd "/tmp"pwdFilePath "/tmp"
Some commands are Shells that emit streams of values. view prints all values in a Shell stream:
view (ls "/usr")FilePath "/usr/lib"FilePath "/usr/src"FilePath "/usr/sbin"FilePath "/usr/include"FilePath "/usr/share"FilePath "/usr/games"FilePath "/usr/local"FilePath "/usr/bin"view (find (suffix "Browser.py") "/usr/lib")FilePath "/usr/lib/python3.4/idlelib/ClassBrowser.py"FilePath "/usr/lib/python3.4/idlelib/RemoteObjectBrowser.py"FilePath "/usr/lib/python3.4/idlelib/PathBrowser.py"FilePath "/usr/lib/python3.4/idlelib/ObjectBrowser.py"
Use fold to reduce the output of a Shell stream:
import qualified Control.Foldl as Foldfold (ls "/usr") Fold.length8fold (find (suffix "Browser.py") "/usr/lib") Fold.headJust (FilePath "/usr/lib/python3.4/idlelib/ClassBrowser.py")
Create files using output:
output "foo.txt" ("123" <|> "456" <|> "ABC")realpath "foo.txt"FilePath "/tmp/foo.txt"
Read in files using input:
stdout (input "foo.txt")123456ABC
Format strings in a type safe way using format:
dir <- pwdformat ("I am in the "%fp%" directory") dir"I am in the /tmp directory"
Commands like grep, sed and find accept arbitrary Patterns
stdout (grep ("123" <|> "ABC") (input "foo.txt"))123ABClet exclaim = fmap (<> "!") (plus digit)stdout (sed exclaim (input "foo.txt"))123!456!ABC
Note that grep and find differ from their Unix counterparts by requiring that the Pattern matches the entire line or file name by default. However, you can optionally match the prefix, suffix, or interior of a line:
stdout (grep (has "2") (input "foo.txt"))123stdout (grep (prefix "1") (input "foo.txt"))123stdout (grep (suffix "3") (input "foo.txt"))123
You can also build up more sophisticated Shell programs using sh in
conjunction with do notation:
{-# LANGUAGE OverloadedStrings #-}
import Turtle
main = sh example
example = do
-- Read in file names from "files1.txt" and "files2.txt"
file <- fmap fromText (input "files1.txt" <|> input "files2.txt")
-- Stream each file to standard output only if the file exists
True <- liftIO (testfile file)
line <- input file
liftIO (echo line)See Turtle.Tutorial for an extended tutorial explaining how to use this library in greater detail.
Print exactly one line to stdout
To print more than one line see printf, which also supports formatted output
Print exactly one line to stderr
Read in a line from stdin
Returns Nothing if at end of input
Deprecated. Use Data.Text.IO.readFile instead
Read in a file as Text
Deprecated. Use Data.Text.IO.writeFile instead
Write out a file as Text
Get command line arguments in a list
Set or modify an environment variable
Note: This will change the current environment for all of your program's threads since this modifies the global state of the process
Delete an environment variable
Look up an environment variable
Retrieve all environment variables
Change the current directory
Note: This will change the current directory for all of your program's threads since this modifies the global state of the process
Get the current directory
Get the home directory
Get the path pointed to by a symlink
Canonicalize a path
Move a file or directory
Works if the two paths are on the same filesystem.
If not, mv will still work when dealing with a regular file,
but the operation will not be atomic
Create a directory
Fails if the directory is present
Create a directory tree (equivalent to mkdir -p)
Does not fail if the directory is present
Copy a file
Copy a directory tree and preserve symbolic links
Copy a directory tree and dereference symbolic links
Create a symlink from one FilePath to another
Remove a file
Remove a directory
Remove a directory tree (equivalent to rm -r)
Use at your own risk
Check if a file exists
Check if a directory exists
Check if a path exists
Get the current time
Get the time a file was last modified
Touch a file, updating the access and modification times to the current time
Creates an empty file if it does not exist
Time how long a command takes in monotonic wall clock time
Returns the duration alongside the return value
Get the system's host name
Show the full path of an executable file
Show all matching executables in PATH, not just the first
Sleep for the given duration
A numeric literal argument is interpreted as seconds. In other words,
(sleep 2.0) will sleep for two seconds.
Exit with the given exit code
An exit code of 0 indicates success
Throw an exception using the provided Text message
Analogous to && in Bash
Runs the second command only if the first one returns ExitSuccess
Analogous to || in Bash
Run the second command only if the first one returns ExitFailure
mktemp :: MonadManaged managed=> FilePathParent directory
-> TextFile name template
-> managed (FilePath, Handle)Create a temporary file underneath the given directory
Deletes the temporary file when done
Note that this provides the Handle of the file in order to avoid a potential race condition from the file being moved or deleted before you have a chance to open the file. The mktempfile function provides a simpler API if you don't need to worry about that possibility.
mktempfile :: MonadManaged managed=> FilePathParent directory
-> TextFile name template
-> managed FilePathCreate a temporary file underneath the given directory
Deletes the temporary file when done
mktempdir :: MonadManaged managed=> FilePathParent directory
-> TextDirectory name template
-> managed FilePathCreate a temporary directory underneath the given directory
Deletes the temporary directory when done
Fork a thread, acquiring an Async value
Wait for an Async action to complete
Change the current directory. Once the current Shell is done, it returns back to the original directory.
:set -XOverloadedStringscd "/"view (pushd "/tmp" >> pwd)FilePath "/tmp"pwdFilePath "/"
Read lines of Text from standard input
Read lines of Text from a file
Stream lines of Text to standard output
Stream lines of Text to a file
Stream lines of Text to append to a file
Stream lines of Text to standard error
Read in a stream's contents strictly
Stream all immediate children of the given directory, excluding "." and
".."
Stream all recursive descendents of the given directory
This skips any directories that fail the supplied predicate
lstree = lsif (\_ -> return True)Stream all recursive descendents of the given directory
Stream the recursive descendents of a given directory between a given minimum and maximum depth
Combine the output of multiple Shells, in order
Keep all lines that match the given Pattern
Replace all occurrences of a Pattern with its Text result
sed performs substitution on a line-by-line basis, meaning that
substitutions may not span multiple lines. Additionally, substitutions may
occur multiple times within the same line, like the behavior of
s/.../.../g.
Warning: Do not use a Pattern that matches the empty string, since it will match an infinite number of times. sed tries to detect such Patterns and die with an error message if they occur, but this detection is necessarily incomplete.
Like sed, but the provided substitution must match the beginning of the line
Like sed, but the provided substitution must match the end of the line
Like sed, but the provided substitution must match the entire line
Update a file in place using a Shell transformation
For example, this is used to implement the inplace* family of utilities
Search a directory recursively for all files matching the given Pattern
Filter a shell of FilePaths according to a given pattern
A Stream of "y"s
Number each element of a Shell (starting at 0)
A Shell that endlessly emits ()
Limit a Shell to a fixed number of values
NOTE: This is not lazy and will still consume the entire input stream. There is no way to implement a lazy version of this utility.
Limit a Shell to values that satisfy the predicate
This terminates the stream on the first value that does not satisfy the predicate
Cache a Shell's output so that repeated runs of the script will reuse the result of previous runs. You must supply a FilePath where the cached result will be stored.
The stored result is only reused if the Shell successfully ran to completion without any exceptions. Note: on some platforms Ctrl-C will flush standard input and signal end of file before killing the program, which may trick the program into "successfully" completing.
Run a list of IO actions in parallel using fork and wait.
view (parallel [(sleep 3) >> date, date, date])2016-12-01 17:22:10.83296 UTC2016-12-01 17:22:07.829876 UTC2016-12-01 17:22:07.829963 UTC
Filter adjacent duplicate elements:
view (uniq (select [1,1,2,1,3]))1213
Filter adjacent duplicates determined after applying the function to the element:
view (uniqOn fst (select [(1,'a'),(1,'b'),(2,'c'),(1,'d'),(3,'e')]))(1,'a')(2,'c')(1,'d')(3,'e')
Filter adjacent duplicate elements determined via the given function:
view (uniqBy (==) (select [1,1,2,1,3]))1213
Return a list of the sorted elements of the given Shell, keeping duplicates:
sort (select [1,4,2,3,3,7])[1,2,3,3,4,7]
Return a list of the elements of the given Shell, sorted after applying the given function and keeping duplicates:
sortOn id (select [1,4,2,3,3,7])[1,2,3,3,4,7]
Return a list of the elements of the given Shell, sorted by the given function and keeping duplicates:
sortBy (comparing fst) (select [(1,'a'),(4,'b'),(2,'c'),(3,'d'),(3,'e'),(7,'f')])[(1,'a'),(2,'c'),(3,'d'),(3,'e'),(4,'b'),(7,'f')]
Count the number of characters in the stream (like wc -c)
This uses the convention that the elements of the stream are implicitly ended by newlines that are one character wide
Count the number of words in the stream (like wc -w)
Count the number of lines in the stream (like wc -l)
This uses the convention that each element of the stream represents one line
Split a line into chunks delimited by the given Pattern
proc Run a command using execvp, retrieving the exit code
The command inherits stdout and stderr for the current process
shell Run a command line using the shell, retrieving the exit code
This command is more powerful than proc, but highly vulnerable to code injection if you template the command line with untrusted input
The command inherits stdout and stderr for the current process
procs This function is identical to proc except this throws ProcFailed for non-zero exit codes
This function is identical to shell except this throws ShellFailed for non-zero exit codes
inproc Run a command using execvp, streaming stdout as lines of Text
The command inherits stderr for the current process
inshell Run a command line using the shell, streaming stdout as lines of Text
This command is more powerful than inproc, but highly vulnerable to code injection if you template the command line with untrusted input
The command inherits stderr for the current process
Throws an ExitCode exception if the command returns a non-zero exit code
inprocWithErr inshellWithErr Run a command line using the shell, streaming stdout and stderr as lines
of Text. Lines from stdout are wrapped in Right and lines from
stderr are wrapped in Left.
This command is more powerful than inprocWithErr, but highly vulnerable to code injection if you template the command line with untrusted input
Throws an ExitCode exception if the command returns a non-zero exit code
procStrict Run a command using execvp, retrieving the exit code and stdout as a
non-lazy blob of Text
The command inherits stderr for the current process
shellStrict Run a command line using the shell, retrieving the exit code and stdout as a non-lazy blob of Text
This command is more powerful than proc, but highly vulnerable to code injection if you template the command line with untrusted input
The command inherits stderr for the current process
procStrictWithErr Run a command using execvp, retrieving the exit code, stdout, and stderr
as a non-lazy blob of Text
shellStrictWithErr Run a command line using the shell, retrieving the exit code, stdout, and stderr as a non-lazy blob of Text
This command is more powerful than proc, but highly vulnerable to code injection if you template the command line with untrusted input
streamWithErr streamWithErr generalizes inprocWithErr and inshellWithErr by allowing
you to supply your own custom CreateProcess. This is for advanced users
who feel comfortable using the lower-level process API
Throws an ExitCode exception if the command returns a non-zero exit code
systemStrict systemStrict generalizes shellStrict and procStrict by allowing you to
supply your own custom CreateProcess. This is for advanced users who feel
comfortable using the lower-level process API
systemStrictWithErr systemStrictWithErr generalizes shellStrictWithErr and
procStrictWithErr by allowing you to supply your own custom
CreateProcess. This is for advanced users who feel comfortable using
the lower-level process API
This type is the same as System.Directory.Permissions
type except combining the executable and
searchable fields into a single executable field for
consistency with the Unix chmod. This simplification is still entirely
consistent with the behavior of System.Directory, which treats the two
fields as interchangeable.
Eq PermissionsDefined in turtle-1.6.2 · Turtle.PreludeOrd PermissionsDefined in turtle-1.6.2 · Turtle.PreludeRead PermissionsDefined in turtle-1.6.2 · Turtle.PreludeShow PermissionsDefined in turtle-1.6.2 · Turtle.Preludechmod :: MonadIO io=> (Permissions -> Permissions)Permissions update function
-> FilePathPath
-> io PermissionsUpdated permissions
Update a file or directory's user permissions
chmod rwo "foo.txt" -- chmod u=rw foo.txt
chmod executable "foo.txt" -- chmod u+x foo.txt
chmod nonwritable "foo.txt" -- chmod u-w foo.txtThe meaning of each permission is:
readable (+r for short): For files, determines whether you can read
from that file (such as with input). For directories, determines
whether or not you can list the directory contents (such as with ls).
Note: if a directory is not readable then ls will stream an empty list
of contents
writable (+w for short): For files, determines whether you can write
to that file (such as with output). For directories, determines whether
you can create a new file underneath that directory.
executable (+x for short): For files, determines whether or not that
file is executable (such as with proc). For directories, determines
whether or not you can read or execute files underneath that directory
(such as with input or proc)
Get a file or directory's user permissions
Set a file or directory's user permissions
Copy a file or directory's permissions (analogous to chmod --reference)
+r-r+w-w+x-x-r -w -x+r -w -x-r +w -x-r -w +x+r +w -x+r -w +x-r +w +x+r +w +xGet the size of a file or a directory
Construct a Size from an integer in bytes
format sz (B 42)"42 B"
Construct a Size from an integer in kilobytes
format sz (KB 42)"42.0 KB"let B n = KB 1 in n1000
Construct a Size from an integer in megabytes
format sz (MB 42)"42.0 MB"let KB n = MB 1 in n1000
Construct a Size from an integer in gigabytes
format sz (GB 42)"42.0 GB"let MB n = GB 1 in n1000
Construct a Size from an integer in terabytes
format sz (TB 42)"42.0 TB"let GB n = TB 1 in n1000
Construct a Size from an integer in kibibytes
format sz (KiB 42)"43.8 KB"let B n = KiB 1 in n1024
Construct a Size from an integer in mebibytes
format sz (MiB 42)"44.40 MB"let KiB n = MiB 1 in n1024
Construct a Size from an integer in gibibytes
format sz (GiB 42)"45.97 GB"let MiB n = GiB 1 in n1024
Construct a Size from an integer in tebibytes
format sz (TiB 42)"46.179 TB"let GiB n = TiB 1 in n1024
Extract a size in bytes
1 kilobyte = 1000 bytes1 megabyte = 1000 kilobytes1 gigabyte = 1000 megabytes1 terabyte = 1000 gigabytes1 kibibyte = 1024 bytes1 mebibyte = 1024 kibibytes1 gibibyte = 1024 mebibytes1 tebibyte = 1024 gibibytesPOSIX defines operations to get information, such as owner, permissions, size and access times, about a file. This information is represented by the FileStatus type.
Note: see chmod.
Limitations: Support for high resolution timestamps is filesystem dependent:
HFS+ volumes on OS X only support whole-second times.
Get the status of a file
Get the status of a file, but don't follow symbolic links
Size of the file in bytes. Does not follow symlinks
Time of last access
Time of last modification
Time of last status change (i.e. owner, group, link count, mode, etc.)
Checks if this file is a block device.
Checks if this file is a character device.
Checks if this file is a named pipe device.
Checks if this file is a regular file device.
Checks if this file is a directory device.
Checks if this file is a symbolic link device.
Checks if this file is a socket device.
Check if a file was last modified after a given timestamp
Check if a file was last modified before a given timestamp
Show a => Show (WithHeader a)Defined in turtle-1.6.2 · Turtle.PreludeShow ProcFailedDefined in turtle-1.6.2 · Turtle.PreludeException ProcFailedDefined in turtle-1.6.2 · Turtle.PreludeShow ShellFailedDefined in turtle-1.6.2 · Turtle.PreludeException ShellFailedDefined in turtle-1.6.2 · Turtle.Prelude