Skip to content

Instantly share code, notes, and snippets.

@da-tubi
Last active August 22, 2023 08:00
Show Gist options
  • Save da-tubi/99d901e696b72327fc0e0744577e4de4 to your computer and use it in GitHub Desktop.
Save da-tubi/99d901e696b72327fc0e0744577e4de4 to your computer and use it in GitHub Desktop.
Elvish Scripting Basics

Elvish Scripting Basics

Assignment and Substitution

var a = 375
set a = 376

var hello = $a

Variables

Environment Variables

echo $E:HOME
echo $E:USER

Positional Parameters

> elvish -c "echo $args"
[]
> elvish -c "echo $args" 1 2 3
[1 2 3]
> elvish -c "echo $args" --path /path/to -v
[--path /path/to -v]

> elvish -c "echo $args[0]" --path /path/to -v
--path

> elvish -c "count $args" --path /path/to -v
▶ (num 3)

Values

  • $true
  • $false
  • $nil

Branches

if <condition> {
    <body>
} elif <condition> {
    <body>
} else {
    <else-body>
}

Loops

for <var> <container> {
    <body>
} else {
    <body>
}

Commandline and Output Capture

ls

var out = (ls)

Exception and Exeception Capture

try {
}
catch {
}
if ?(test -d name) {
}

Function

fn <name> <lambda>

Parallel

range 1 10 | peach {|x| + $x 10 }

Here is the Scala equiv:

(1 to 10).par.foreach(x => x + 10)

Slides

Elvish Intro

Elvish is an expressive programming language and a versatile interactive shell, combined into one seamless package. It runs on Linux, BSDs, macOS and Windows.

I'm using Elvish 0.19.2, and Elvish is implemented in Go.

The Key of Shell Scripting

  • Concise
  • Cross Platform: GNU coreutils
    • Windows
    • macOS/Linux
  • Versatile expression
    • e.g. String manipulation in Bash Scripting is extremely hard

Shell Scripting:

rm -rf .git/

Python:

import subprocess
subprocess.call(["rm", "-rf", ".git/"])

Each

Sample 1

all [ 1 2 3 4 5 ] | each {|x|
  + $x 1
}

Sample 2

all [ 1 2 3 4 5 ] | each {|x|
  + $x 1
} | each {|x|
  + $x 2
}

Sample 3

each {|x| + $x 1} [1 2 3 4 5]

Filter

fn filter {|pred @rest|
  each {|x|
    if ($pred $x) {
      put $x
    }
  } $@rest
}

put 1 2 3 args each | each { |x|
  put $x.elv
} | filter { |file_name|
  if ?(test -f $file_name) { put $true } else { put $false }
} | each { |x|
  echo $x
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment