### Download and Verify Elvish Binary using External Commands Source: https://elv.sh/first-commands This example demonstrates how to use a sequence of external commands within an Elvish terminal to download the Elvish binary, verify its SHA-256 checksum, and then unpack it. It showcases `curl` for downloading, `shasum` (Unix) or `certutil` (Windows) for checksum verification, and `tar` for archive extraction, illustrating a common workflow for software installation. ```Shell ~> curl -s -o elvish-HEAD.tar.gz https://dl.elv.sh/linux-amd64/elvish-HEAD.tar.gz ~> curl -s https://dl.elv.sh/linux-amd64/elvish-HEAD.tar.gz.sha256sum 93b206f7a5b7f807f6b2b2b99dd4074ed678620541f6e9742148fede0a5fefdb elvish-HEAD.tar.gz ~> shasum -a 256 elvish-HEAD.tar.gz # On a Unix system 93b206f7a5b7f807f6b2b2b99dd4074ed678620541f6e9742148fede0a5fefdb elvish-HEAD.tar.gz ~> certutil -hashfile elvish-HEAD.tar.gz SHA256 # On Windows 93b206f7a5b7f807f6b2b2b99dd4074ed678620541f6e9742148fede0a5fefdb ~> tar -xvf elvish-HEAD.tar.gz x elvish ~> ./elvish ``` -------------------------------- ### Start Elvish Shell Source: https://elv.sh/first-commands Demonstrates the command to launch the Elvish shell from a standard terminal prompt, initiating an interactive Elvish session. ```Shell $ elvish ``` -------------------------------- ### Download Elvish archive with hardcoded platform Source: https://elv.sh/variables-and-loops Initial Elvish commands to download the Elvish HEAD archive and display its SHA256 checksum. This example hardcodes the 'linux-amd64' platform, which is addressed in subsequent sections for portability. ```elvish curl -s -o elvish-HEAD.tar.gz https://dl.elv.sh/linux-amd64/elvish-HEAD.tar.gz curl -s https://dl.elv.sh/linux-amd64/elvish-HEAD.tar.gz.sha256sum ``` -------------------------------- ### Elvish Command Options Source: https://elv.sh/tour Demonstrates how Elvish commands accept options, which are specified as map-like key-value pairs. The example shows the `echo` command using the `sep` option to change its output separator. ```Elvish echo &sep=',' foo bar echo &sep="\n" foo bar ``` -------------------------------- ### Elvish Lambdas with Arguments and Options (Signature) Source: https://elv.sh/tour Explains how to define lambdas with a signature that includes positional arguments and named options. The example shows a lambda accepting two arguments and an optional parameter with a default value, demonstrating how to call it with and without the option. ```Elvish var f = {|a b &opt=default| echo "a = "$a echo "b = "$b echo "opt = "$opt } $f foo bar $f foo bar &opt=option ``` -------------------------------- ### Elvish Initial Download and Checksum Commands Source: https://elv.sh/variables-and-loops This snippet presents a set of repetitive `curl` commands used for downloading an Elvish binary and its corresponding SHA256 checksum. It serves as an example of commands that can be optimized by introducing variables to store common parts, reducing redundancy. ```Terminal - elvish ~> curl -s -o elvish-HEAD.tar.gz https://dl.elv.sh/$platform:os'-'$platform:arch/elvish-HEAD.tar.gz ~> curl -s https://dl.elv.sh/$platform:os'-'$platform:arch/elvish-HEAD.tar.gz.sha256sum f1b2e7c149f5104c191bc7c9cd922b87ac73d810ba71c186636d1807e2a5ce95 elvish-HEAD.tar.gz ``` -------------------------------- ### Define Server Hosts for Parallel Updates in Elvish Source: https://elv.sh/scripting-case-studies This Elvish snippet initializes a list of server hosts, each defined with a name and a specific command to execute for updates. It forms the initial setup for a larger script designed to perform parallel updates across multiple servers. ```Elvish var hosts = [[&name=a &cmd='apt update'] [&name=b &cmd='pacman -Syu']] ``` -------------------------------- ### Defining a custom Elvish module Source: https://elv.sh/tour Shows the content of an Elvish `.elv` file for defining a custom module. This example defines a simple function `f` that can be exported and used by other Elvish scripts. ```Elvish fn f { echo 'in a function in foo' } ``` -------------------------------- ### Generate Random Integer with Elvish `randint` Source: https://elv.sh/first-commands Shows how to use the `randint` command to generate a random integer within a specified range, serving as a digital dice example. ```Elvish randint 1 7 ``` -------------------------------- ### Elvish `range` Command Example Source: https://elv.sh/value-types Illustrates the behavior of the `range` command in Elvish. This example shows how `range` generates a sequence of numbers, starting from the first argument and stopping *before* reaching the second argument, demonstrating its use in creating numerical sequences. ```Elvish ~> range 2905 2900 ▶ (num 2905) ▶ (num 2904) ▶ (num 2903) ▶ (num 2902) ▶ (num 2901) ``` -------------------------------- ### Convert JPG to PNG Files Source: https://elv.sh/scripting-case-studies This example demonstrates how to convert all .jpg files in the current directory to .png files using GraphicsMagick. It showcases Elvish's simplified variable handling and command-based string manipulation compared to traditional shell scripting. ```Elvish for x [*.jpg] { gm convert $x (str:trim-suffix $x .jpg) } ``` ```Shell for x in *.jpg do gm convert "$x" "${x%.jpg}".png done ``` -------------------------------- ### Elvish History Walking: Filter by Prefix Source: https://elv.sh/tour Illustrates how to filter command history by typing a prefix before initiating history walking. This example shows retrieving previous `echo` commands. ```Elvish ~> echo (styled warning: red) bumpy road elf@host HISTORY #2 ``` -------------------------------- ### Elvish String Trimming Example with str:trim-suffix Source: https://elv.sh/variables-and-loops This snippet provides a direct example of using the `str:trim-suffix` command in Elvish. It demonstrates how to remove a specified suffix from a string, which is useful for manipulating filenames or other text data. ```Elvish str:trim-suffix banana.jpg .jpg ▶ banana ``` -------------------------------- ### Elvish Interactive Pipeline for Streaming Outputs Source: https://elv.sh/effective-elvish This interactive example demonstrates the parallel execution and streaming nature of Elvish pipelines. Commands in a pipeline run concurrently, processing input as it becomes available, leading to immediate feedback and efficient use of multi-core processors. ```Elvish ~> each $str:to-upper~ | each {|x| put $x$x } (Start typing) abc ▶ ABCABC xyz ▶ XYZXYZ (Press ^D) ``` -------------------------------- ### Execute a Custom Elvish Function Source: https://elv.sh/organizing-and-reusing-code Illustrates how to call the previously defined `jpg-to-avif` function with example image filenames. This demonstrates the function's usage after it has been defined in the current Elvish session. ```Elvish jpg-to-avif unicorn.jpg jpg-to-avif banana.jpg ``` -------------------------------- ### Analyze Git Commits with a Unix Pipeline Source: https://elv.sh/pipelines-and-io An elaborate example of a Unix pipeline using `git log`, `sort`, `uniq`, and `head` to find and rank the top 10 committers in a Git repository by commit count. ```Shell (Unix) git log --format=%an | sort | uniq -c | sort -nr | head -n 10 ``` -------------------------------- ### Elvish Directory History: Filter Visited Directories Source: https://elv.sh/tour Shows how to filter the list of visited directories by typing a search term. This example filters for paths containing 'local'. ```Elvish ~> elf@host LOCATION local 10 ~/.local/share/elvish 9 /usr/local 9 /usr/local/share 9 /usr/local/bin ``` -------------------------------- ### Elvish Variable Definition with `var` Command Source: https://elv.sh/variables-and-loops This example demonstrates how to define a new variable, `archive-url`, using the `var` command in Elvish. By storing a common URL part in a variable, subsequent commands become more concise and maintainable. It also clarifies that the `$` prefix is used for variable evaluation, not definition. ```Terminal - elvish ~> var archive-url = https://dl.elv.sh/$platform:os'-'$platform:arch/elvish-HEAD.tar.gz ~> curl -s -o elvish-HEAD.tar.gz $archive-url ~> curl -s $archive-url.sha256sum f1b2e7c149f5104c191bc7c9cd922b87ac73d810ba71c186636d1807e2a5ce95 elvish-HEAD.tar.gz ``` -------------------------------- ### Elvish Number Type Creation Source: https://elv.sh/tour Explains how to create typed numbers in Elvish using the `num` builtin command, as there is no dedicated literal syntax for numbers. It shows examples for integers and scientific notation. ```Elvish num 1 num 1e2 ``` -------------------------------- ### Chain Multiple Filters with Pipes for Specific Content Source: https://elv.sh/pipelines-and-io Extends the previous example by chaining two `grep` or `findstr` commands to further filter `curl` output, specifically for lines containing both 'HEAD' and 'linux'. ```Shell (Unix) curl -s https://dl.elv.sh/INDEX | grep HEAD | grep linux ``` ```Shell (Windows) curl -s https://dl.elv.sh/INDEX | findstr HEAD | findstr linux ``` -------------------------------- ### Implementing `grep` in Elvish Source: https://elv.sh/effective-elvish Provides an example of implementing a custom `grep`-like function in Elvish. It demonstrates using the `re` module for regular expression matching and processing input line by line to filter content. ```Elvish ~> use re ~> fn mygrep {|p| each {|line| if (re:match $p $line) { echo $line } } } ~> cat in.txt abc 123 lorem 456 ~> cat in.txt | mygrep '[0-9]' 123 456 ``` -------------------------------- ### Parallel Server Updates with Nested Data Structures in Elvish Source: https://elv.sh/scripting-case-studies This Elvish example showcases the use of more complex, nested data structures to define hosts, including dotfiles for each. The `peach` command then leverages these structures to perform both SSH updates and SCP file transfers in parallel, demonstrating Elvish's flexibility with structured data. ```Elvish var hosts = [[&name=a &cmd='apt update' &dotfiles=[.tmux.conf .gitconfig]] [&name=b &cmd='pacman -Syu' &dotfiles=[.vimrc]]] peach {|h| ssh root@$h[name] $h[cmd] > ssh-$h[name].log scp ~/(all $h[dotfiles]) root@$h[name]: } $hosts ``` -------------------------------- ### Using a Custom Elvish Module from Terminal Source: https://elv.sh/organizing-and-reusing-code This example shows how to import and use the previously defined `img` custom module in the Elvish terminal. After `use img`, functions like `img:jpg-to-avif` can be called, demonstrating module command execution. ```Elvish ~> use img ~> img:jpg-to-avif unicorn.jpg ``` -------------------------------- ### Elvish Prompt Customization: Left Prompt Source: https://elv.sh/tour Illustrates how to customize the left prompt (`edit:prompt`) in Elvish. This example uses `tilde-abbr` for the current directory and `styled` for a custom prompt symbol, resulting in a fancy Unicode prompt. ```Elvish ~> set edit:prompt = { tilde-abbr $pwd styled '❱ ' bright-red } ~❱ # Fancy unicode prompts! elf✸host.example.com ``` -------------------------------- ### Elvish `each` Command with Pipe Input (Verbose for Small Sets) Source: https://elv.sh/effective-elvish This example demonstrates providing input to the `each` command via a pipe using the `put` command. While generally preferred for larger or dynamic inputs, it can be more verbose for small, static input sets compared to direct argument passing. ```Elvish ~> put lorem ipsum | each $str:to-upper~ ▶ LOREM ▶ IPSUM ``` -------------------------------- ### Filtering File Content with Input Redirection Source: https://elv.sh/pipelines-and-io Demonstrates how to filter lines containing a specific pattern ('Elvish') from a file (`input.txt`) using input redirection (`<`). This example shows both the Unix `grep` command and the Windows `findstr` command, illustrating cross-platform equivalents for text processing. ```Unix Shell grep Elvish < input.txt ``` ```Windows Shell findstr Elvish < input.txt ``` -------------------------------- ### Using an Elvish Module from a Subdirectory in Terminal Source: https://elv.sh/organizing-and-reusing-code This example demonstrates how to import and use an Elvish module located in a subdirectory (e.g., `myutils/img`). The `use` command specifies the full path, but module commands are still accessed using only the base module name, like `img:jpg-to-avif`. ```Elvish ~> use myutils/img ~> img:jpg-to-avif unicorn.jpg ``` -------------------------------- ### Filtering Terminal Input with Output Redirection Source: https://elv.sh/pipelines-and-io Shows how to run a command that expects input directly from the terminal, while redirecting its output to a file. The command waits for user input, which is then processed. This is useful for small amounts of interactive input. Examples are given for `grep` on Unix and `findstr` on Windows. ```Unix Shell grep Elvish > output.txt ``` ```Windows Shell findstr Elvish > output.txt ``` -------------------------------- ### Create and Run a Basic Elvish Script Source: https://elv.sh/organizing-and-reusing-code Demonstrates how to create a simple 'Hello, world!' script by saving commands to a `.elv` file and then executing it from the Elvish terminal. This introduces the concept of Elvish scripts for formal code organization. ```Elvish echo 'Hello, world!' ``` ```Elvish elvish hello.elv ``` -------------------------------- ### Elvish Script Abort on Failure Example Source: https://elv.sh/scripting-case-studies Illustrates Elvish's default behavior of aborting an entire script if any command within it fails. This is presented as a safer default for scripting, especially in CI/CD pipelines, as it prevents subsequent commands from running after a critical failure, unlike traditional shell scripts. ```Elvish ./run-tests ./run-linters ``` -------------------------------- ### Print 'Hello, World!' in Elvish Source: https://elv.sh/first-commands Illustrates the basic 'command + arguments' structure in Elvish using the `echo` command to print a simple string to the console. ```Elvish echo Hello, world! ``` -------------------------------- ### Elvish Navigation Mode: Filesystem Browser Source: https://elv.sh/tour Demonstrates the built-in filesystem navigator, activated by `Ctrl-N`. This mode allows browsing files and directories, with the ability to insert selected filenames into the main buffer. ```Elvish ~/elvish> elf@host NAVIGATING Ctrl-H hidden Ctrl-F filter bash 1.0-release.m 1.0 has not been released y elvis CONTRIBUTING. zsh Dockerfile LICENSE Makefile PACKAGING.md README.md SECURITY.md cmd go.mod go.sum pkg │ syntaxes │ ``` -------------------------------- ### Redirecting Filtered Output to a File Source: https://elv.sh/pipelines-and-io Illustrates how to filter content from an input file and redirect the resulting output to a new file. This combines both input (`<`) and output (`>`) redirection, useful for processing data and saving results without displaying them on the terminal. Examples are provided for both Unix `grep` and Windows `findstr`. ```Unix Shell grep Elvish < input.txt > output.txt ``` ```Windows Shell findstr Elvish < input.txt > output.txt ``` -------------------------------- ### Elvish Function with Explicit Empty Argument List Source: https://elv.sh/organizing-and-reusing-code This Elvish function `up` is functionally equivalent to the previous example but explicitly shows an empty argument list `||`. This syntax highlights Elvish's function definition structure, where `||` denotes that the function takes no arguments. ```elvish fn up {|| brew upgrade } ``` -------------------------------- ### Elvish Early Error Detection: Variable Not Found (Detailed) Source: https://elv.sh/scripting-case-studies Building on the previous example, this snippet highlights Elvish's precise error reporting. It demonstrates how Elvish not only detects the misspelt variable but also pinpoints the exact location of the error within the line, aiding in quick debugging. ```Elvish ~> var project = ~/project ~> rm -rf $projetc/bin elf@host compilation error: [interactive]:1:8-15: variable $projetc not found ``` -------------------------------- ### Import and Use Elvish `math` Module Source: https://elv.sh/first-commands Illustrates how to import a module (e.g., `math`) and then access commands or functions (e.g., `pow`) provided by that module, showcasing modular command access. ```Elvish use math # import the "math" module math:pow 2 10 # raise 2 to the power of 10 ``` -------------------------------- ### Elvish Custom Function: POSIX Alias Emulation Source: https://elv.sh/tour Provides an example of defining an Elvish function to emulate POSIX aliases. This function redefines `ls` to always use `--color`, ensuring the external `ls` command is called via `e:` prefix. ```Elvish fn ls {|@a| e:ls --color $@a } ``` -------------------------------- ### Portable Elvish archive download using variables Source: https://elv.sh/variables-and-loops Shows how to construct a portable download URL for the Elvish archive by dynamically incorporating the '$platform:os' and '$platform:arch' variables. This makes the commands adaptable to different systems without hardcoding platform-specific paths. ```elvish curl -s -o elvish-HEAD.tar.gz https://dl.elv.sh/$platform:os'-'$platform:arch/elvish-HEAD.tar.gz curl -s https://dl.elv.sh/$platform:os'-'$platform:arch/elvish-HEAD.tar.gz.sha256sum ``` -------------------------------- ### Elvish Correct Quoting for String Concatenation and Syntax Highlighting Source: https://elv.sh/variables-and-loops This example illustrates the correct way to concatenate a literal string (like a hyphen) with variables in Elvish by quoting the literal part. It also shows how Elvish's syntax highlighting visually distinguishes quoted literals from variable names, providing a clear indication of how the shell interprets the command. ```Terminal - elvish ~> echo $platform:os'-'$platform:arch darwin-arm64 ~> echo $platform:os-$platform:arch Exception: variable $platform:os- not found ``` -------------------------------- ### Elvish: Rational and Floating-Point Number Operations Source: https://elv.sh/value-types Illustrates Elvish's support for rational and floating-point numbers in arithmetic operations. It provides examples of adding fractions and decimal numbers. ```Elvish + 1/2 1/3 + 0.2 0.3 ``` -------------------------------- ### Elvish Value Pipelines with each Source: https://elv.sh/tour Demonstrates how Elvish pipelines can operate on values. A command outputting values can pipe them directly to a command that consumes values, such as `each`, which applies a lambda to each incoming value. ```Elvish put foo bar | each {|x| echo 'I got '$x } ``` -------------------------------- ### Capture Command Output in Elvish Source: https://elv.sh/tour Shows how to capture the output of a command and use it as a value in Elvish using `()`, similar to command substitution in traditional shells, to find details about a binary. ```elvish ~> ls -l (which elvish) -rwxr-xr-x 1 xiaq users 7813495 Mar 2 21:32 /home/xiaq/go/bin/elvish ``` -------------------------------- ### Loading Host Configurations from JSON in Elvish Source: https://elv.sh/scripting-case-studies This Elvish script demonstrates how to dynamically load host configurations from an external JSON file using `from-json`. It then uses the `peach` command to execute parallel SSH and SCP operations based on the data retrieved from the JSON, enhancing script reusability and maintainability. ```Elvish var hosts = (from-json < hosts.json) peach {|h| ssh root@$h[name] $h[cmd] > ssh-$h[name].log scp ~/(all $h[dotfiles]) root@$h[name]: } $hosts ``` -------------------------------- ### Sequence Commands in Elvish Source: https://elv.sh/tour Demonstrates how to run multiple commands sequentially in Elvish using a semicolon `;` or a newline. This allows for executing commands one after another. ```elvish ~> echo a; echo b a b ~> echo a echo b a b ``` -------------------------------- ### Elvish: User-Defined Function with Redundant `put` Source: https://elv.sh/effective-elvish An example of a user-defined function `split-by-comma` that explicitly uses `put` to 'return' the result of `str:split`. This pattern is often redundant as commands inherently write to structured output. ```Elvish ~> fn split-by-comma {|s| use str; put (str:split , $s) } ~> split-by-comma foo,bar ▶ foo ▶ bar ``` -------------------------------- ### Elvish External Command Existence and Path Lookup Source: https://elv.sh/tour Explains how to check for the existence of external commands using `has-external` and how to query their full path using `search-external` in Elvish, providing utilities for managing external program interactions. ```APIDOC has-external (command_name: string) Purpose: Checks if a specified external command exists in the system's PATH. ``` ```APIDOC search-external (command_name: string) Purpose: Queries and returns the full path of a specified external command. ``` -------------------------------- ### Access Map Values by Key in Elvish Source: https://elv.sh/value-types Illustrates how to retrieve a specific value from an Elvish map using key-based indexing. This example directly processes the output of `from-json` to extract the 'country' field. ```Elvish curl -s https://api.myip.com | put (from-json)[country] ▶ Elvendom ``` -------------------------------- ### Elvish and Bash Environment Variable Handling Source: https://elv.sh/tour Illustrates how Elvish handles environment variables using the E: prefix and the env command for temporary settings. This is compared to Bash's export command for making variables available to child processes and direct assignment. ```Elvish echo $E:HOME set E:foo = bar { tmp E:foo = bar; some-command } env foo=bar some-command ``` ```Bash echo $HOME export foo=bar export foo; foo=bar some-command ``` -------------------------------- ### Access Elvish built-in platform variables Source: https://elv.sh/variables-and-loops Demonstrates how to use the 'platform' module and access built-in variables like '$platform:os' and '$platform:arch' to dynamically determine the operating system and CPU architecture within Elvish. This allows for platform-agnostic scripting. ```elvish use platform echo $platform:os echo $platform:arch ``` -------------------------------- ### Elvish Compilation Error Example: Unassigned Variable Source: https://elv.sh/unique-semantics Shows how Elvish handles errors during the compilation phase. If an unassigned variable is used, Elvish will detect this as a compilation error and prevent the entire code chunk from executing. ```elvish # assuming $nonexistent was not assigned echo before echo $nonexistent ``` -------------------------------- ### Elvish `for` command Source: https://elv.sh/tour Illustrates the Elvish `for` loop, iterating over a list of string values. For each item, a lambda is executed, demonstrating how to construct strings within the loop. ```Elvish ~> for x [expressive versatile] { echo "Elvish is "$x } ``` -------------------------------- ### Elvish List Variable Assignment and Inspection Source: https://elv.sh/unique-semantics Demonstrates how to assign a list to a variable in Elvish, and then use `kind-of` to check its type and `count` to get the number of elements. This illustrates that lists are first-class data structures in Elvish. ```Elvish ~> var li = [foo bar 'lorem ipsum'] ~> kind-of $li # "kind" is like type ▶ list ~> count $li # count the number of elements in a list ▶ 3 ``` -------------------------------- ### XKCD JSON API Reference Source: https://elv.sh/value-types Documentation for the XKCD JSON API, detailing the endpoints and expected responses for fetching comic information. This API is used by the Elvish value pipeline example to retrieve comic data. ```APIDOC XKCD JSON API: Base URL: https://xkcd.com/ Endpoints: GET /info.0.json Description: Fetches information for the latest comic. Returns: JSON object with comic details. Example Keys: - "num": Comic number (integer) - "title": Comic title (string) GET /{comic_number}/info.0.json Description: Fetches information for a specific comic by its number. Parameters: - comic_number (integer): The number of the comic to retrieve. Returns: JSON object with comic details. Example Keys: - "num": Comic number (integer) - "title": Comic title (string) ``` -------------------------------- ### Elvish Tilde Expansion Source: https://elv.sh/tour Demonstrates how tilde expansion works in Elvish, allowing users to refer to their own home directory (~) or another user's home directory (~username) in file paths, consistent with traditional shell behavior. ```Elvish ~> echo ~/foo /home/me/foo ``` ```Elvish ~> echo ~elf/foo /home/elf/foo ``` -------------------------------- ### Use Byte Pipelines in Elvish Source: https://elv.sh/tour Demonstrates the use of byte pipelines in Elvish, which function like traditional UNIX pipelines, by filtering output from `head` with `grep`. ```elvish ~> cat a.txt foo barx lorem quux lux nox ~> head -n4 a.txt | grep x barx quux ``` -------------------------------- ### Elvish Tab Completion: Initial state Source: https://elv.sh/tour Demonstrates the initial state of Elvish's tab completion feature. After typing a command and pressing Tab, Elvish presents a list of possible arguments or filenames, along with a 'COMPLETING argument' indicator. ```Elvish ~> cd elvish ~/elvish> echo 1.0-release.md elf@host COMPLETING argument 1.0-release.md README.md syntaxes/ CONTRIBUTING.md SECURITY.md tools/ Dockerfile cmd/ vscode/ LICENSE go.mod website/ Makefile go.sum PACKAGING.md pkg/ ``` -------------------------------- ### Elvish History Listing: Full Command History Source: https://elv.sh/tour Shows how to list the entire command history using `Ctrl-R`. The output displays a numbered list of previously executed commands, which can be filtered and navigated. ```Elvish ~> elf@host HISTORY (dedup on) Ctrl-D dedup 3 echo "hello\nbye" > /tmp/x │ 4 from-lines < /tmp/x │ 5 cd /tmp 6 cd ~/elvish 7 git branch 8 git checkout . 9 git commit 19 git status 20 cd /usr/local/bin 21 echo $pwd 22 * (+ 3 4) (- 100 94) 31 make 32 math:min 3 1 30 ``` -------------------------------- ### Elvish Exception: Arity mismatch Source: https://elv.sh/tour Demonstrates an exception thrown in Elvish when a function is called with an incorrect number of arguments. The example shows a function defined to take no arguments being called with two, resulting in an 'arity mismatch' error. ```Elvish ~> var f = { echo foo } # doesn't take arguments ~> $f a b Exception: arity mismatch: arguments here must be 0 values, but is 2 values [tty 2], line 1: $f a b ``` -------------------------------- ### Elvish `use` command for importing modules Source: https://elv.sh/tour Demonstrates importing a built-in module (`str`) using the `use` command. After import, functions from the module can be called by prepending their namespace (e.g., `str:to-upper`). ```Elvish ~> use str ~> str:to-upper foo ▶ FOO ``` -------------------------------- ### Run Elvish Script with Arguments (Initial Behavior) Source: https://elv.sh/organizing-and-reusing-code This terminal command executes the `hello.elv` script with arguments `foo` and `bar`. It illustrates the initial behavior where the script does not yet process command-line arguments, outputting a default greeting regardless of the provided input. ```terminal ~> elvish hello.elv foo bar Hello, world! ``` -------------------------------- ### Elvish String Manipulation with Pipes Source: https://elv.sh/effective-elvish This example performs the same string manipulation as the previous one but utilizes Elvish's pipe operator. This approach significantly improves readability by allowing data to flow from left to right, mirroring natural language descriptions of the algorithm. ```Elvish ~> var csv = a,b,foo,bar ~> use str ~> str:split , $csv | each {|x| put $x,$x } | str:join ';' ▶ 'a,a;b,b;foo,foo;bar,bar' ``` -------------------------------- ### JSON Configuration for Host Definitions Source: https://elv.sh/scripting-case-studies This JSON snippet provides an external configuration format for defining hosts, including their names, commands, and associated dotfiles. This allows for easy sharing and customization of host parameters without modifying the main Elvish script. ```JSON [ {"name": "a", "cmd": "apt update", "dotfiles": [".tmux.conf", ".gitconfig"]}, {"name": "b", "cmd": "pacman -Syu", "dotfiles": [".vimrc"]} ] ``` -------------------------------- ### Elvish Parse Error Example: Unclosed Parenthesis Source: https://elv.sh/unique-semantics Illustrates how Elvish handles syntax errors during the parsing phase. If a chunk of code contains an unclosed parenthesis, Elvish will reject the entire chunk and not execute any part of it, printing a parse error. ```elvish echo before echo ( ``` -------------------------------- ### Perform File Redirections in Elvish Source: https://elv.sh/tour Illustrates basic input and output redirection in Elvish, similar to traditional shells, by saving the first 10 lines of a file to another file. ```elvish ~> head -n10 < a.txt > a1.txt ``` -------------------------------- ### Perform Basic Arithmetic in Elvish Source: https://elv.sh/first-commands Demonstrates Elvish's approach to arithmetic operations, such as addition and multiplication, which follow a 'Polish notation' style where the operator precedes its arguments. ```Elvish + 2 10 # addition * 2 10 # multiplication ``` -------------------------------- ### Elvish Function Returning List with `echo` (Incorrect) Source: https://elv.sh/unique-semantics Illustrates an attempt to return a list from an Elvish function using the `echo` command. This example shows that `echo` serializes the list into a string, losing its original structure, and how output capture then treats it as a string. ```Elvish ~> fn f { echo [foo bar 'lorem ipsum'] } ~> var li = (f) # (...) is output capture, like $(...) in other shells ~> kind-of $li ▶ string ~> count $li # count the number of bytes, since $li is now a string ▶ 23 ``` -------------------------------- ### Elvish: Putting Multiple File Matches Source: https://elv.sh/variables-and-loops Demonstrates how a wildcard expression like `*.jpg` evaluates to multiple distinct values, which the `put` command then outputs individually. ```Elvish put *.jpg ``` -------------------------------- ### Automated Image Conversion with Elvish For Loop and List Source: https://elv.sh/variables-and-loops This Elvish code snippet illustrates how to automate image conversion using a `for` loop and a predefined list of filenames. It shows the `use str` command for module import and `str:trim-suffix` for dynamic filename generation. ```Elvish use str ~> for jpg [banana.jpg unicorn.jpg] { var avif = (str:trim-suffix $jpg .jpg).avif gm convert $jpg $avif } ``` -------------------------------- ### Chaining Sequential Arithmetic Operations in Elvish Source: https://elv.sh/arguments-and-outputs Illustrates how to perform multiple arithmetic operations sequentially in Elvish, where the result of one command is manually used as input for the next. This highlights a less efficient method compared to capturing outputs directly. ```Elvish ~> + 2 10 ▶ (num 12) ~> * 3 12 ▶ (num 36) ``` -------------------------------- ### Run Background Jobs in Elvish Source: https://elv.sh/tour Explains how to run a command in the background in Elvish by appending `&` to the pipeline. Notes the difference from traditional shells regarding command separation with `&`. ```elvish ~> echo foo & foo job echo foo & finished ``` -------------------------------- ### Elvish List and Map Indexing Source: https://elv.sh/tour Demonstrates how to access elements within lists and maps using indexing. Lists support zero-based indexing and slicing, while maps are indexed by their keys. ```Elvish put $li[0] put $li[1..3] put $map[k1] ``` -------------------------------- ### Elvish Variable Field Splitting Source: https://elv.sh/tour Details Elvish's approach to variable field splitting, noting that it does not perform automatic `$IFS` splitting. It provides examples of how to explicitly split strings into fields using `str:fields` or by 'exploding' a list of strings. ```Elvish ~> var foo = 'a b c d' ~> touch $foo # Creates one file ``` ```Elvish ~> var args-as-string = 'a b c d' ~> use str ~> touch (str:fields $args-as-string) # creates four files ``` ```Elvish ~> var args-as-list = [a b c d] ~> touch $@args-as-list # also creates four files ``` -------------------------------- ### Elvish and Bash Tilde Expansion Source: https://elv.sh/tour Shows the use of tilde expansion (~) in both Elvish and Bash to represent the user's home directory. This feature provides a convenient shorthand for path references in both shells. ```Elvish echo ~/foo ``` ```Bash echo ~/foo ``` -------------------------------- ### Elvish Lambda Definition and Basic Usage Source: https://elv.sh/tour Introduces lambdas as first-class values in Elvish, showing how to define them using curly braces and assign them to variables. It also demonstrates executing a lambda and inspecting its value. ```Elvish var f = { echo "I'm a lambda" } $f put $f var g = (put $f) $g ``` -------------------------------- ### Elvish Conditional File Conversion with `os:exists` Source: https://elv.sh/value-types Extends a file conversion example to include a conditional check. This snippet iterates through JPG files and converts them to AVIF only if the target AVIF file does not already exist, utilizing the `os:exists` command for the check. ```Elvish ~> use os ~> use str ~> for jpg [*.jpg] { var avif = (str:trim-suffix $jpg .jpg).avif if (not (os:exists $avif)) { # new condition gm convert $jpg $avif } } ``` -------------------------------- ### Elvish Prompt Customization: Right Prompt Source: https://elv.sh/tour Shows how to customize the right prompt (`edit:rprompt`) in Elvish using a function that displays styled user and hostname information. It uses `constantly` and `styled` commands. ```Elvish ~> set edit:rprompt = (constantly ^ (styled (whoami)✸(hostname) inverse)) ``` -------------------------------- ### Elvish Pipeline with `put` and `take` for Structured Data Source: https://elv.sh/unique-semantics Demonstrates using the `take` command in an Elvish pipeline to retain a fixed number of structured items from the value-oriented channel. This example shows how various data types (list, string with newline, map) can be passed and processed. ```Elvish ~> put [lorem ipsum] "foo\nbar" [&key=value] | take 2 ▶ [lorem ipsum] ▶ "foo\nbar" ``` -------------------------------- ### Elvish Environment Variable: Setting PATH Directly Source: https://elv.sh/tour Demonstrates setting the `PATH` environment variable directly in Elvish using the `E:` prefix. This method is similar to traditional shell `PATH` assignments. ```Elvish set E:PATH = /opts/bin:/bin:/usr/bin ``` -------------------------------- ### Elvish Quoting Command Names and Arguments Source: https://elv.sh/arguments-and-outputs Shows that Elvish allows quoting not only arguments but also command names themselves. This demonstrates the flexibility of quoting, though it's generally unnecessary and reduces readability for simple commands. ```elvish ~> '+' '2' '10' ▶ (num 12) ~> 'randint' '1' '7' ▶ (num 3) ``` -------------------------------- ### Elvish Value Output with put Source: https://elv.sh/tour Illustrates Elvish's unique value output mechanism using the `put` command. Values can include strings, lists, maps, and closures, providing richer data handling than byte output. ```Elvish put foo [foo] [&foo=bar] { put foo } ``` -------------------------------- ### Elvish and Bash I/O Redirections Source: https://elv.sh/tour Compares input and output redirection syntax in Elvish and Bash. Both shells use the standard < for input and > for output redirection, demonstrating a consistent approach to file I/O. ```Elvish head -n10 < a.txt > b.txt ``` ```Bash head -n10 < a.txt > b.txt ``` -------------------------------- ### Traditional Shell Behavior: Misspelt Variable Evaluation Source: https://elv.sh/scripting-case-studies This example contrasts Elvish's error handling with that of a traditional shell. It shows how a misspelt variable in a traditional shell might silently evaluate to an empty string, potentially leading to unintended and destructive commands like `rm -rf /bin`. ```Shell $ project=~/project $ rm -rf $projetc/bin [ ...] ``` -------------------------------- ### Manual Image Conversion with GraphicsMagick in Terminal Source: https://elv.sh/variables-and-loops This snippet demonstrates the manual, repetitive process of converting individual image files (JPG to AVIF) using the `gm convert` command. It highlights the inefficiency of this approach when dealing with multiple files. ```Terminal gm convert banana.jpg banana.avif ~> gm convert unicorn.jpg unicorn.avif ~> # and so on... ``` -------------------------------- ### Elvish Directory History: List Visited Directories Source: https://elv.sh/tour Illustrates how to list recently visited directories using `Ctrl-L`. The output shows a numbered list of paths, which can be navigated and selected to change the current directory. ```Elvish ~> elf@host LOCATION 10 ~/elvish 10 ~/.local/share/elvish 10 ~/elvish/website 10 ~/.config/elvish 9 ~/elvish/pkg/edit 9 ~/elvish/pkg/eval 9 /opt 9 /usr/local 9 /usr/local/share 9 /usr/local/bin 9 /usr 9 /tmp │ 8 ~/zsh │ ``` -------------------------------- ### Demonstrating Copy-on-Assignment in Elvish Source: https://elv.sh/unique-semantics This Elvish example shows that when a map is assigned to another variable, it appears to be copied. Changes made to the new variable's map do not affect the original map, indicating a distinct assignment semantic where the value is copied rather than referenced. The `put $m[foo]` command confirms the original map remains unchanged. ```Elvish var m = [&foo=bar &lorem=ipsum] var m2 = $m set m2[foo] = quux put $m[foo] ``` -------------------------------- ### Temporarily Set Elvish Environment Variables Source: https://elv.sh/tour Compares using `tmp` and the external `env` command to temporarily set environment variables for a command execution in Elvish, showing both approaches achieve similar results. ```elvish ~> { tmp E:foo = bar; bash -c 'echo $foo' } bar ~> env foo=bar bash -c 'echo $foo' bar ``` -------------------------------- ### Performing Basic Arithmetic in Elvish Source: https://elv.sh/arguments-and-outputs Demonstrates fundamental arithmetic operations like addition and multiplication directly in the Elvish terminal. It shows how numerical results are displayed as typed numbers, indicated by the `▶ (num ...)` notation. ```Elvish ~> + 2 10 # addition ▶ (num 12) ~> * 2 10 # multiplication ▶ (num 20) ``` -------------------------------- ### Capturing Multiple Elvish Values into a List or Multiple Variables Source: https://elv.sh/effective-elvish This example illustrates two correct methods for capturing multiple values returned by an Elvish expression. The first method explicitly constructs a list using square brackets around the expression. The second, more concise method, uses rest variables (prefixed with '@') to directly assign the multiple returned values. ```Elvish ~> use str ~> var li = [(str:split , a,b,c)] ~> put $li ▶ [a b c] ~> var @li = (str:split , a,b,c) # equivalent and slightly shorter ``` -------------------------------- ### Elvish Script Processing Command-Line Arguments Source: https://elv.sh/organizing-and-reusing-code This Elvish script `hello.elv` demonstrates how to access and process command-line arguments passed to a script via the `$args` variable. It checks if arguments are present; if not, it prints 'Hello, world!', otherwise, it iterates through each argument to greet them individually. ```elvish if (== 0 (count $args)) { echo 'Hello, world!' } else { for who $args { echo 'Hello, '$who'!' } } ``` -------------------------------- ### Elvish External Command Prefix `e:` Source: https://elv.sh/tour Explains how to explicitly treat a command as an external command in Elvish by prefixing it with `e:`. This ensures that Elvish does not interpret the command as an internal function or alias, directing it to the system's command search path. ```APIDOC e: Purpose: Forces Elvish to treat a command as an external command, bypassing internal interpretations. ``` -------------------------------- ### Elvish Tab Completion: Filtering candidates Source: https://elv.sh/tour Shows how Elvish's tab completion dynamically filters the list of candidates as the user continues typing. This allows for quickly narrowing down suggestions to find the desired argument. ```Elvish ~> cd elvish ~/elvish> echo 1.0-release.md elf@host COMPLETING argument .md 1.0-release.md PACKAGING.md SECURITY.md CONTRIBUTING.md README.md ``` -------------------------------- ### Elvish For Loop for Batch Image Conversion with Wildcard Source: https://elv.sh/variables-and-loops This advanced Elvish snippet showcases the power of `for` loops combined with wildcard patterns (`*.jpg`) to process an unknown number of files. It efficiently converts all JPG files in a directory to AVIF format, demonstrating scalability. ```Elvish use str ~> for jpg [*.jpg] { var avif = (str:trim-suffix $jpg .jpg).avif gm convert $jpg $avif } ``` -------------------------------- ### Access and Set Elvish Environment Variables Source: https://elv.sh/tour Shows how to access environment variables in Elvish using the `E:` namespace and how to set them. Explains that Elvish environment variables are always 'exported'. ```elvish ~> echo $E:HOME /home/elf ~> set E:PATH = /bin:/sbin ``` -------------------------------- ### Using a custom Elvish module Source: https://elv.sh/tour Illustrates how to import and use a custom Elvish module defined in a `.elv` file. Once imported with `use`, functions within the module can be invoked using their namespace. ```Elvish ~> use foo ~> foo:f in a function in foo ``` -------------------------------- ### Elvish: Expanding List to Multiple Values with 'all' Source: https://elv.sh/variables-and-loops Illustrates the `all` command, which takes a list as input and expands its elements into separate multiple values. ```Elvish all [foo bar] ``` -------------------------------- ### Elvish Exception: External command non-zero exit Source: https://elv.sh/tour Shows how Elvish converts a non-zero exit code from an external command (like `false`) into an exception, providing a unified error handling mechanism. ```Elvish ~> false Exception: false exited with 1 [tty 3], line 1: false ``` -------------------------------- ### Listing Elvish Command History with Ctrl-R Source: https://elv.sh/arguments-and-outputs Illustrates the `Ctrl-R` shortcut to enter Elvish's history listing mode, which provides a searchable and selectable list of past commands. This mode is useful for finding commands that are not immediately recent. ```Elvish ~> elf@host HISTORY (dedup on) Ctrl-D dedup 21 echo $pwd │ 22 * (+ 3 4) (- 100 94) │ 31 make │ 32 math:min 3 1 30 33 randint 1 7 ``` -------------------------------- ### Define a Simple Elvish Alias for System Upgrade Source: https://elv.sh/organizing-and-reusing-code This Elvish function `up` acts as a simple alias to execute `brew upgrade`. It demonstrates defining a function without explicit arguments, useful for common system maintenance tasks like daily package upgrades. ```elvish fn up { brew upgrade } ``` -------------------------------- ### Elvish and Bash Byte Pipelines Source: https://elv.sh/tour Shows the use of byte pipelines (|) in Elvish to connect the standard output of one command to the standard input of another. This functionality is identical to Bash's standard piping mechanism. ```Elvish head -n4 a.txt | grep x ``` ```Bash head -n4 a.txt | grep x ``` -------------------------------- ### Elvish `try...catch` for exception handling Source: https://elv.sh/tour Illustrates how to catch exceptions in Elvish using the `try` command. The `catch` block executes if an exception occurs within the `try` block, allowing for graceful error recovery. ```Elvish ~> try { false } catch e { echo 'got an exception' } ```