WolframScript Tutorial

By Xah Lee. Date: . Last updated: .
Xah Talk Show 2021-11-20 Bash vs PowerShell vs WolframLang

This is a tutorial on using WolframScript to do typical linux shell scripting tasks, such as bash and PowerShell.

Download Wolfram Engine

Get Wolfram Language Free

What is WolframScript

WolframScript is a command line interface to Wolfram Engine. It lets you run WolframLang code from a terminal. It talks to a wolfram engine on local machine or on remote machine.

Wolfram Engine comes with WolframScript bundled.

Run WolframScript in terminal

Start by typing wolframscript

WolframScript math 2021-10-22 FYBv
WolframScript math 2021-10-22

Quit/Exit WolframScript

Type Exit or Quit.

Run a WolframLang code

wolframscript -code "3+1"

Run a WolframLang file

wolframscript -file test.wls

Get help for options

wolframscript -h

Here's a complete list:

-h, -help
Print help text.
-c WL, -code WL
Give Wolfram Language code to execute.
-f, -file PATH
Give a file containing Wolfram Language code to execute.
-a, -api URL|UUID
Use an API at the specified URL, or coming from a cloud or local object with the specified UUID. Provide arguments in the form 'key=value' following '-args'.
-fun, -function WL
Use a function whose arguments are the strings given using '-args' interpreted as the types given using '-signature'
-o, -cloud [CLOUDBASE]
Execute code in the cloud, using the specified cloud base. By default, cloud base is https://wolframcloud.com
-l, -local [KERNELPATH]
Execute code locally, using the specified path to the Wolfram Engine kernel. By default, KernelPath uses the most recent version of the Wolfram Language found on the local system.
-- ARGS...,-args ARGS...
Used with '-api' or '-function' to provide arguments.
-s, -signature TYPE...
Used with '-function' and '-args' to specify interpreter types for provided arguments.
-v, -verbose
Print additional information during execution.
-activate [KEY]
Activate the Wolfram Engine through the cloud or with a key.
-entitlement ID
Activate the Wolfram Engine using on-demand licensing with the given license entitlement ID.
-authenticate [ID PASS]
Authenticate with the cloud, specifying a particular Wolfram ID and password, and prompting if they are not given. Different authentication can be specified for different clouds.
-disconnect
Disconnect from the cloud, removing authentication information.
-configure [KEY=VAL...]
Configure WolframScript by specifying values for particular configuration variable keys. If no keys are given, this prints the current configuration.
-version
Print version of WolframScript.
-username USERNAME
Give username for authentication.
-password PASSWORD
Give password for authentication.
-permissionskey KEY
Give a permissions key used to authorize access to a cloud deployed API.
-k, -noverifypeer
Disable peer certificate verification when interacting with the cloud.
-timeout SECONDS [VALUE]
Specify the number of seconds to allow for execution. Return value if time is exceeded.
-charset ENCODING
Use encoding for output. Encodings can be None to output raw bytes, or any entry in $CharacterEncodings except "Unicode". The default is to infer the value from the terminal's language settings.
-format TYPE
Specify the format in which to give output. Any format understood by Export can be used.
-print [all]
When running a script, print the result from executing the last line of the script, or each line if all is given.
-linewise
Execute code on each line of standard input that is read.
-script ARGS...
Counterpart to wolfram -script, additionally sets up $ScriptCommandLine.

WolframScript file extension

.wls
WolframScript file extension.
.wl
Generic WolframLang file extension.
.m
WolframLang (Mathematica) package file extension.
.nb
WolframLang (Mathematica) notebook file extension.

WolframLang Tutorial for Shell Tasks

The following is a tutorial on WolframLang on shell tasks, similar to what you would use bash or PowerShell for.

You should first read the following:

List Files

list all files in current directory. Result is a list of paths: {"path1", "path2" }

FileNames[]

list all files ending in html:

FileNames["*html","c:/Users/xah/M/"]

list all files ending in html or css:

FileNames[{"*html", "*css"}, "c:/Users/xah/"]

list all files ending in html or css, in several directories:

FileNames[{"*html", "*css"}, {"c:/Users/xah/Documents/", "c:/Users/xah/Downloads/"}]

list all files, including any subdirectory to infinite depth:

FileNames[{"*html", "*css"}, {"c:/Users/xah/Documents/", "c:/Users/xah/Downloads/"}, Infinity]

Current Directory

Directory[]
return current dir path.
SetDirectory[]
set current dir path to home path.
SetDirectory["path"]
set current dir to path.
ResetDirectory[]
set current dir to last.
DirectoryStack[]
return a list of directories of previous current directories.

Delete Directory

(* delete a dir only if empty *)
DeleteDirectory["c:/Users/x09908"]
(* delete a dir and all its files and subdirs *)
DeleteDirectory["c:/Users/x09908",DeleteContents->True]

DeleteDirectory returns Null if it succeeds in deleting a directory, and $Failed if it fails.

Check is File or Dir

DirectoryQ["c:/Users/xah/abc.txt"]
(* False *)

DirectoryQ["c:/Users/xah/"]
(* True *)
(* is file *)
FileType[ "c:/Users/xah/web/xahlee_info/M/WolframScript.html" ] === File

(* is dir *)
FileType[ "c:/Users/xah/" ] === Directory

(* doesn't exist *)
FileType[ "c:/Users/xah/tt" ] === None

Check File/Dir Existence

(* check file exist *)
FileExistsQ["c:/Users/xah/abc.txt"]
(* True *)

(* works on dir too *)
FileExistsQ["c:/Users/xah/"]
(* True *)

Directory Path, File Name, File Extension

FileNameSplit["c:/Users/xah/abc.txt"]
(* {c:, Users, xah, abc.txt} *)
FileBaseName["c:/Users/xah/abc.txt"] == "cat"
FileExtension["c:/Users/xah/abc.txt"] == "txt"
FileNameDepth["c:/Users/xah/abc.txt"] == 4

more

FileNameJoin[dir,name]
join directory and file name into a single path.
FileNameTake[path]
return the filename part.
FileNameDrop[path]
return the directory part.
NotebookFileName[]
return full path of current notebook. (fail if not running from notebook)
ExpandFileName[name]
return full path (name relative to current directory).
AbsoluteFileName[name]
return a cononical full path.

Get File Date

get file date:

FileDate["c:/Users/xah/documents", "Creation"] //DateString
(* Thu 7 Jan 2021 23:27:29 *)

FileDate["c:/Users/xah/documents", "Modification"] //DateString
(* Wed 27 Oct 2021 10:14:25 *)

FileDate["c:/Users/xah/documents", "Access"] //DateString
(* Mon 22 Nov 2021 20:42:58 *)

Date and Time

Now
return current date and time.
DateString[]
return current datetime string.
DateString[date]
convert date to string.
DateString[date, format]
use format. Named format includes:
  • "Date" full date → Thursday 4 April 2019
  • "DateShort" short date → Thu 4 Apr 2019
  • "Time" full time → 15:57:49
  • "DateTime" full date and time → Thursday 4 April 2019 15:57:57
  • "DateTimeShort" short date and time → Thu 4 Apr 2019 15:58:08
  • "ISODate" ISO-8601 date → 2019-04-04
  • "ISODateTime" ISO date and time → 2019-04-04T15:58:57
and more.
DateString[ ]
(* Mon 22 Nov 2021 21:25:08 *)

DateString[ Now , "ISODate" ]
(* 2021-11-22 *)

DateString[ Now , "ISODateTime" ]
(* 2021-11-22T21:25:08 *)

File Size

get file size:

FileSize["c:/Users/xah/abc.txt"] // Print
(* Quantity[4.681, Kilobytes] *)

Print File Content

print whole file:

FilePrint["c:/Users/xah/abc.txt"]

print just first 9 lines:

FilePrint["c:/Users/xah/abc.txt", 9]

print last 9 lines:

FilePrint["c:/Users/xah/abc.txt", -9]

read/get file content

ReadString["c:/Users/xah/some.html"]

write to file

WriteString[ "c:/Users/xah/some.txt", "something" ]

replace string

StringReplace["some elephant and wolfs", "elephant"->"tiger"]

replace multiple pairs of strings:

(* replace multiple pairs of strings. replacement does not depend on previous replacement. *)

StringReplace["abc", {"a"->"x", "b"->"y", "x"->"H"}]
(* xyc *)

File Hash

FileHash[path]
return integer hash code of file content at path.
FileHash[path,"type"]
use hash algorithm type. Supported type includes "MD5", "SHA256", "SHA3-256" and more.
FileHash[ "c:/Users/xah/web/xahlee_info/M/WolframScript.html" ]
(* sample return 196936574075229334718916868727866708509 *)

map function to files

FileSystemMap

load WolframScript

load, eval a WolframScript

(*
content of the file is
f =  (x|-> x+1)
*)

(* load the file *)
Get["c:/Users/xah/x1/xx.m"]

Print[f[3]]
(* prints 4 *)

WolframLang Tutorial