Skip to main content
  1. Lumesh Cases/

Simple Script Examples

1066 words·6 mins
Table of Contents

Simple Examples to OPerate Data Structure via Lumesh.

  • Directly access nested properties
1let user = {
2    name: "Alice",
3    profile: {
4        age: 25,
5        skills: ["rust", "javascript", "python"]
6    }
7}
8user.profile.skills@1  # Output: "javascript"
  • Chained calls
11...10 | .map(x -> x * 2) | .filter(x -> x > 10)
2# Chained calls, clear and intuitive
  • Loop dispatch pipeline
1ls -1 |> print "-->" _ "<--"
  • Structured pipeline
1df -H | Into.table() | pprint
2Fs.ls -l | where(size > 5K) | select(name,size,modified)
  • Error capture
16 / 0 ?.               # Ignore error
26 / 0 ?: x -> print x  # Handle error
  • Data debugging
1let a := (x) -> x + 1
2debug a
  • Mapping operations
 1# Mapping transformation
 2let data = {a: 1, b: 2, c: 3}
 3
 4# Transform keys and values simultaneously
 5let result = Map.map(
 6    k -> k.to_upper(),     # Key transformation function
 7    v -> v * 2,           # Value transformation function
 8    data
 9)
10# Result: {A: 2, B: 4, C: 6}

Practical Examples
#

File Handling:
#

  • Find files larger than 5KB modified within the last 24 hours and display in a table:

    1Fs.ls -l ./src/ | where(size > 5K) | where (Fs.diff('d',modified) > 1) | pprint
  • Backup all .rs source files in the current directory and its subdirectories:

    1. Method 1: Using loop dispatch pipeline
    1  ls **/*.rs |> cp _ ./backup/
    1. Method 2: Using loop
    1  for f in **/*.rs {
    2      cp _ ./backup
    3  }
  • Remove comments from a file and save:

    1. Method 1: Functional
    1let content = Fs.read("data.txt")
    2let lines = content.lines()
    3let filtered = lines | List.filter(line -> !line.starts_with('#'))
    4# Write result
    5filtered.join('\n') | Fs.write("output.txt")
    1. Method 2: Using chained calls
    1Fs.read("data.txt").lines().filter(x -> !x.starts_with('#')) >> "output.txt"
    1. Method 3: Using chained pipeline
    1Fs.read("data.txt") | .lines() | .filter(x -> !x.starts_with('#')) >> "output.txt"

System Management
#

  • Find user processes with CPU usage over 2% and display in a table
1 ps u -u1000 | Into.table() | where(Into.float(CPU) > 2.0) | pprint
  • Find processes using more than 10% of memory
1ps u -u1000 | Into.table() | where(Into.float(MEM) > 10.0) | pprint

Network Operations
#

  • Request JSON data and interpret it as a table
1# HTTP request
2curl 'https://jsonplaceholder.typicode.com/posts/1/comments' | From.json() | pprint
3
4# Further filtering
5curl 'https://jsonplaceholder.typicode.com/posts/1/comments' | From.json() | where(id < 3) | select(name,email) | pprint
  • Request JSON data and save in other formats
1let a = curl 'https://jsonplaceholder.typicode.com/posts/1/comments' | From.json()
2a >> data.json                         # JSON format
3a | Into.csv() >> data.csv         # CSV format
4a | Into.toml() >> data.toml       # TOML format
5
6# a is already a valid Lumesh expression
7type a     # List
8len(a)     # Can perform other regular operations

Operations and Maintenance Scripts
#

  • Write a script to let users select mountable disks
 1let sel = ( lsblk -rno 'name,type,size,mountpoint,label,fstype' | Into.table([name,'type',size,mountpoint,label,fstype]) \
 2    | where($type != 'disk' && !$mountpoint && $fstype !~: 'member') \
 3    | Ui.pick "which to mount:") ?: { print 'no device selected' }
 4
 5if $sel {
 6    let src = (sel.type == 'part' ? `/dev/${sel.name}` : `/dev/mapper/${sel.name}`)
 7    let point = (sel.label == None ? sel.name : sel.label)
 8    let dest = `/run/user/${id - u}/media/${point}`
 9    if !Fs.exists($dest) { mkdir -p $dest }
10    sudo mount -m -o 'defaults,noatime' $src $dest ?: \
11        e -> { notify-send 'Mount Failed' $e.msg; exit 1 }
12    notify-send 'Mount' `device $src mounted`
13}

Common Built-in Modules
#

File System Module (Fs)
#

 1# Directory operations
 2Fs.ls("/path")              # List directory contents
 3Fs.mkdir("new_dir")         # Create directory
 4Fs.rm("empty_dir")          # Remove empty directory
 5
 6# File operations
 7Fs.read("file.txt")         # Read file
 8Fs.write("file.txt", data)  # Write to file
 9Fs.append("Log.txt", entry) # Append content
10
11# Path operations
12Fs.exists("/path/to/file")  # Check if path exists
13Fs.is_dir("/path")          # Check if it is a directory
14Fs.canon("./relative/path")  # Get absolute path

System Directory Access
#

1# Get system directories
2let dirs = Fs.dirs()
3println(dirs.home)      # User home directory
4println(dirs.config)    # Configuration directory
5println(dirs.cache)     # Cache directory
6println(dirs.current)   # Current working directory

Detailed File List Information
#

1# ls command options
2Fs.ls -l        # Detailed information
3Fs.ls -a        # Show hidden files
4Fs.ls -L        # Follow symbolic links
5Fs.ls -u        # Show user information
6Fs.ls -m        # Show permission mode
7Fs.ls -p        # Show full path

Common Built-in Functions
#

Core Functions
#

 1# Data operations
 2len(collection)             # Get length
 3type(value)                 # Get type
 4rev("string")               # Reverse string/list
 5flatten([[1,2],[3,4]])      # Flatten nested structure
 6
 7# Execution control
 8eval(expression)            # Evaluate expression
 9exec_str("let x = 10")      # Execute string code
10include("script.lm")        # Include file into current environment
11import("module.lm")         # Import module into new environment

Data Querying and Filtering
#

 1# Data table operations
 2let users = [
 3    {name: "Alice", age: 25, active: True},
 4    {name: "Bob", age: 30, active: False},
 5    {name: "Carol", age: 35, active: True}
 6]
 7
 8# Filter rows
 9let active_users = where(active, users)
10
11# Select columns
12let names_ages = select(name, age, users)

Command Execution System
#

External Command Execution
#

Lumesh supports various command execution modes:

1# Basic command execution
2ls -la
3
4# Background execution
5command &
6
7# Silent execution
8command &-

PTY Support
#

For programs requiring terminal interaction, Lumesh provides PTY support:

1# Automatically determine and enable PTY mode
2ls -l | vi
3
4# Force PTY mode (for interactive programs), generally not needed
5ls -l |^ vi
6'' |^ vi 'file.txt'

Script Execution
#

Script Runner
#

Lumesh provides two execution modes:

1# Directly execute command
2lumesh -c "print 'Hello World'"
3
4# Execute script file
5lumesh script.lm arg1 arg2
6
7# Access parameters in the script
8println(argv[0])  # First parameter

Test Example
#

 1#!/usr/bin/env lumesh
 2
 3# Test function
 4fn assert(actual, expected, test_name) {
 5    if actual != expected {
 6        print "[FAIL]" test_name "| Actual: " actual "| Expected: " expected
 7    } else {
 8        print "[PASS]" test_name
 9    }
10}
11
12# Variable assignment test
13let x = 10
14assert(str(x), "10", "Single Variable Assignment")
15
16# Delayed assignment test
17x := 2 + 3
18assert(eval(x), 5, "Delayed Assignment Evaluation")

Logging System
#

Log Level Management
#

 1# Set log level
 2Log.set_level(Log.level.info)    # Set to INFO level
 3
 4# Check log level
 5if Log.enabled(1) {
 6    Log.debug("Debugging enabled")
 7}
 8Log.info("Debug information")
 9
10# Disable logging
11Log.disable()

Learn more:

Related