nushell

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Nushell - Modern Structured Shell

Nushell - 现代化结构化Shell

This skill activates when working with Nushell (Nu), writing Nu scripts, working with structured data pipelines, or configuring the Nu environment.
当你使用Nushell(简称Nu)、编写Nu脚本、处理结构化数据管道或配置Nu环境时,可使用本指南。

When to Use This Skill

何时使用本指南

Activate when:
  • Writing Nushell scripts or commands
  • Working with structured data in pipelines
  • Converting from bash/zsh to Nushell
  • Configuring Nushell environment
  • Processing JSON, CSV, YAML, or other structured data
  • Creating custom commands or modules
适用于以下场景:
  • 编写Nushell脚本或命令
  • 在管道中处理结构化数据
  • 从bash/zsh迁移到Nushell
  • 配置Nushell环境
  • 处理JSON、CSV、YAML或其他结构化数据
  • 创建自定义命令或模块

What is Nushell?

什么是Nushell?

Nushell is a modern shell that:
  • Treats data as structured (not just text streams)
  • Works cross-platform (Windows, macOS, Linux)
  • Provides clear error messages and IDE support
  • Combines shell and programming language features
  • Has built-in data format support (JSON, CSV, YAML, TOML, XML, etc.)
Nushell是一款现代化Shell,具备以下特性:
  • 数据视为结构化格式(而非纯文本流)
  • 支持跨平台运行(Windows、macOS、Linux)
  • 提供清晰的错误提示与IDE支持
  • 融合Shell与编程语言的特性
  • 内置对多种数据格式的支持(JSON、CSV、YAML、TOML、XML等)

Installation

安装

bash
undefined
bash
undefined

macOS

macOS

brew install nushell
brew install nushell

Linux (cargo)

Linux (cargo)

cargo install nu
cargo install nu

Windows

Windows

winget install nushell
winget install nushell

Or download from https://www.nushell.sh/

Or download from https://www.nushell.sh/

undefined
undefined

Basic Concepts

基础概念

Everything is Data

一切皆数据

Unlike traditional shells where everything is text, Nu works with structured data:
nu
undefined
与传统Shell中所有内容都是文本不同,Nu以结构化数据为核心:
nu
undefined

Traditional shell (text output)

传统Shell(文本输出)

ls | grep ".txt"
ls | grep ".txt"

Nushell (structured data)

Nushell(结构化数据)

ls | where name =~ ".txt"
undefined
ls | where name =~ ".txt"
undefined

Pipeline Philosophy

管道设计理念

Data flows through pipelines as structured tables/records:
nu
undefined
数据以结构化表格/记录的形式在管道中流转:
nu
undefined

Each command outputs structured data

每个命令输出结构化数据

ls | where size > 1kb | sort-by modified | reverse
undefined
ls | where size > 1kb | sort-by modified | reverse
undefined

Data Types

数据类型

Basic Types

基础类型

nu
undefined
nu
undefined

Integers

整数

42 -10
42 -10

Floats

浮点数

3.14 -2.5
3.14 -2.5

Strings

字符串

"hello" 'world'
"hello" 'world'

Booleans

布尔值

true false
true false

Null

空值

null
undefined
null
undefined

Collections

集合类型

nu
undefined
nu
undefined

Lists

列表

[1 2 3 4 5] ["apple" "banana" "cherry"]
[1 2 3 4 5] ["apple" "banana" "cherry"]

Records (like objects/dicts)

记录(类似对象/字典)

{name: "Alice", age: 30, city: "NYC"}
{name: "Alice", age: 30, city: "NYC"}

Tables (list of records)

表格(记录的列表)

[ {name: "Alice", age: 30} {name: "Bob", age: 25} ]
undefined
[ {name: "Alice", age: 30} {name: "Bob", age: 25} ]
undefined

Ranges

范围类型

nu
undefined
nu
undefined

Number ranges

数值范围

1..10 1..2..10 # Step by 2
1..10 1..2..10 # 步长为2

Use in commands

在命令中使用

1..5 | each { |i| $i * 2 }
undefined
1..5 | each { |i| $i * 2 }
undefined

Working with Files and Directories

文件与目录操作

Navigation

导航

nu
undefined
nu
undefined

Change directory

切换目录

cd /path/to/dir
cd /path/to/dir

List files (returns structured table)

列出文件(返回结构化表格)

ls
ls

List with details

查看详细信息

ls | select name size modified
ls | select name size modified

Filter files

过滤文件

ls | where type == file ls | where size > 1mb ls | where name =~ ".txt$"
undefined
ls | where type == file ls | where size > 1mb ls | where name =~ ".txt$"
undefined

File Operations

文件操作

nu
undefined
nu
undefined

Create file

创建文件

"hello" | save hello.txt
"hello" | save hello.txt

Read file

读取文件

open hello.txt
open hello.txt

Append to file

追加内容到文件

"world" | save -a hello.txt
"world" | save -a hello.txt

Copy

复制

cp source.txt dest.txt
cp source.txt dest.txt

Move/rename

移动/重命名

mv old.txt new.txt
mv old.txt new.txt

Remove

删除

rm file.txt rm -r directory/
rm file.txt rm -r directory/

Create directory

创建目录

mkdir new-dir
undefined
mkdir new-dir
undefined

File Content

文件内容处理

nu
undefined
nu
undefined

Read as string

以字符串形式读取

open file.txt
open file.txt

Read structured data

读取结构化数据

open data.json open config.toml open data.csv
open data.json open config.toml open data.csv

Write structured data

写入结构化数据

{name: "Alice", age: 30} | to json | save user.json [{a: 1} {a: 2}] | to csv | save data.csv
undefined
{name: "Alice", age: 30} | to json | save user.json [{a: 1} {a: 2}] | to csv | save data.csv
undefined

Pipeline Operations

管道操作

Filtering

过滤

nu
undefined
nu
undefined

Filter with where

使用where过滤

ls | where size > 1mb ls | where type == dir ls | where name =~ "test"
ls | where size > 1mb ls | where type == dir ls | where name =~ "test"

Multiple conditions

多条件过滤

ls | where size > 1kb and type == file
undefined
ls | where size > 1kb and type == file
undefined

Selecting Columns

选择列

nu
undefined
nu
undefined

Select specific columns

选择特定列

ls | select name size
ls | select name size

Rename columns

重命名列

ls | select name size | rename file bytes
undefined
ls | select name size | rename file bytes
undefined

Sorting

排序

nu
undefined
nu
undefined

Sort by column

按列排序

ls | sort-by size ls | sort-by modified
ls | sort-by size ls | sort-by modified

Reverse sort

反向排序

ls | sort-by size | reverse
ls | sort-by size | reverse

Multiple columns

多列排序

ls | sort-by type size
undefined
ls | sort-by type size
undefined

Transforming Data

数据转换

nu
undefined
nu
undefined

Map over items with each

使用each遍历并转换

1..5 | each { |i| $i * 2 }
1..5 | each { |i| $i * 2 }

Update column

更新列

ls | update name { |row| $row.name | str upcase }
ls | update name { |row| $row.name | str upcase }

Insert column

插入新列

ls | insert size_kb { |row| $row.size / 1000 }
ls | insert size_kb { |row| $row.size / 1000 }

Upsert (update or insert)

插入或更新列

ls | upsert type_upper { |row| $row.type | str upcase }
undefined
ls | upsert type_upper { |row| $row.type | str upcase }
undefined

Aggregation

聚合

nu
undefined
nu
undefined

Count items

统计数量

ls | length
ls | length

Sum

求和

[1 2 3 4 5] | math sum
[1 2 3 4 5] | math sum

Average

求平均值

[1 2 3 4 5] | math avg
[1 2 3 4 5] | math avg

Min/Max

最小值/最大值

ls | get size | math max ls | get size | math min
ls | get size | math max ls | get size | math min

Group by

分组

ls | group-by type
undefined
ls | group-by type
undefined

Variables

变量

Variable Assignment

变量赋值

nu
undefined
nu
undefined

Let (immutable by default)

Let(默认不可变)

let name = "Alice" let age = 30 let colors = ["red" "green" "blue"]
let name = "Alice" let age = 30 let colors = ["red" "green" "blue"]

Mut (mutable)

Mut(可变)

mut counter = 0 $counter = $counter + 1
undefined
mut counter = 0 $counter = $counter + 1
undefined

Using Variables

变量使用

nu
undefined
nu
undefined

Reference with $

使用$引用变量

let name = "Alice" print $"Hello, ($name)!"
let name = "Alice" print $"Hello, ($name)!"

In pipelines

在管道中使用

let threshold = 1mb ls | where size > $threshold
undefined
let threshold = 1mb ls | where size > $threshold
undefined

Environment Variables

环境变量

nu
undefined
nu
undefined

Get environment variable

获取环境变量

$env.PATH $env.HOME
$env.PATH $env.HOME

Set environment variable

设置环境变量

$env.MY_VAR = "value"
$env.MY_VAR = "value"

Load from file

从文件加载

load-env { API_KEY: "secret" }
undefined
load-env { API_KEY: "secret" }
undefined

String Operations

字符串操作

String Interpolation

字符串插值

nu
undefined
nu
undefined

String interpolation with ()

使用()进行字符串插值

let name = "Alice" print $"Hello, ($name)!"
let name = "Alice" print $"Hello, ($name)!"

With expressions

结合表达式

let x = 5 print $"Result: (5 * $x)"
undefined
let x = 5 print $"Result: (5 * $x)"
undefined

String Methods

字符串方法

nu
undefined
nu
undefined

Case conversion

大小写转换

"hello" | str upcase # HELLO "WORLD" | str downcase # world
"hello" | str upcase # HELLO "WORLD" | str downcase # world

Trimming

去除空格

" spaces " | str trim
" spaces " | str trim

Replace

替换

"hello world" | str replace "world" "nu"
"hello world" | str replace "world" "nu"

Contains

包含判断

"hello world" | str contains "world" # true
"hello world" | str contains "world" # true

Split

分割

"a,b,c" | split row ","
undefined
"a,b,c" | split row ","
undefined

Conditionals

条件判断

If Expressions

If表达式

nu
undefined
nu
undefined

If-else

If-else结构

if $age >= 18 { print "Adult" } else { print "Minor" }
if $age >= 18 { print "成年人" } else { print "未成年人" }

If-else if-else

If-else if-else结构

if $score >= 90 { "A" } else if $score >= 80 { "B" } else { "C" }
if $score >= 90 { "A" } else if $score >= 80 { "B" } else { "C" }

Ternary-style with match

三元表达式风格

let status = if $is_active { "active" } else { "inactive" }
undefined
let status = if $is_active { "活跃" } else { "非活跃" }
undefined

Match (Pattern Matching)

Match(模式匹配)

nu
undefined
nu
undefined

Match expression

Match表达式

match $value { 1 => "one" 2 => "two" _ => "other" }
match $value { 1 => "一" 2 => "二" _ => "其他" }

With conditions

带条件的匹配

match $age { 0..17 => "minor" 18..64 => "adult" _ => "senior" }
undefined
match $age { 0..17 => "未成年人" 18..64 => "成年人" _ => "老年人" }
undefined

Loops

循环

For Loop

For循环

nu
undefined
nu
undefined

Loop over range

遍历范围

for i in 1..5 { print $i }
for i in 1..5 { print $i }

Loop over list

遍历列表

for name in ["Alice" "Bob" "Charlie"] { print $"Hello, ($name)" }
for name in ["Alice" "Bob" "Charlie"] { print $"Hello, ($name)" }

Loop over files

遍历文件

for file in (ls | where type == file) { print $file.name }
undefined
for file in (ls | where type == file) { print $file.name }
undefined

While Loop

While循环

nu
undefined
nu
undefined

While loop

While循环

mut i = 0 while $i < 5 { print $i $i = $i + 1 }
undefined
mut i = 0 while $i < 5 { print $i $i = $i + 1 }
undefined

Each (Functional)

Each(函数式遍历)

nu
undefined
nu
undefined

Transform each item

转换每个元素

1..5 | each { |i| $i * 2 }
1..5 | each { |i| $i * 2 }

With index

带索引遍历

["a" "b" "c"] | enumerate | each { |item| print $"($item.index): ($item.item)" }
undefined
["a" "b" "c"] | enumerate | each { |item| print $"($item.index): ($item.item)" }
undefined

Custom Commands

自定义命令

Defining Commands

定义命令

nu
undefined
nu
undefined

Simple command

简单命令

def greet [name: string] { print $"Hello, ($name)!" }
greet "Alice"
def greet [name: string] { print $"Hello, ($name)!" }
greet "Alice"

With return value

带返回值的命令

def add [a: int, b: int] { $a + $b }
let result = add 5 3
def add [a: int, b: int] { $a + $b }
let result = add 5 3

With default values

带默认值的命令

def greet [name: string = "World"] { print $"Hello, ($name)!" }
undefined
def greet [name: string = "World"] { print $"Hello, ($name)!" }
undefined

Command Parameters

命令参数

nu
undefined
nu
undefined

Required parameters

必填参数

def copy [source: path, dest: path] { cp $source $dest }
def copy [source: path, dest: path] { cp $source $dest }

Optional parameters

可选参数

def greet [ name: string --loud (-l) # Flag --repeat (-r): int = 1 # Named parameter with default ] { let message = if $loud { $name | str upcase } else { $name }
1..$repeat | each { print $"Hello, ($message)!" } }
def greet [ name: string --loud (-l) # 标志位 --repeat (-r): int = 1 # 带默认值的命名参数 ] { let message = if $loud { $name | str upcase } else { $name }
1..$repeat | each { print $"Hello, ($message)!" } }

Usage

使用示例

greet "Alice" greet "Bob" --loud greet "Charlie" --repeat 3
undefined
greet "Alice" greet "Bob" --loud greet "Charlie" --repeat 3
undefined

Pipeline Commands

管道命令

nu
undefined
nu
undefined

Accept pipeline input

接收管道输入

def filter-large [] { where size > 1mb }
def filter-large [] { where size > 1mb }

Usage

使用示例

ls | filter-large
ls | filter-large

Accept and transform pipeline

接收并转换管道输入

def double [] { each { |value| $value * 2 } }
[1 2 3] | double
undefined
def double [] { each { |value| $value * 2 } }
[1 2 3] | double
undefined

Working with Structured Data

结构化数据处理

JSON

JSON

nu
undefined
nu
undefined

Read JSON

读取JSON

let data = open data.json
let data = open data.json

Parse JSON string

解析JSON字符串

let obj = '{"name": "Alice", "age": 30}' | from json
let obj = '{"name": "Alice", "age": 30}' | from json

Write JSON

写入JSON

{name: "Alice", age: 30} | to json | save user.json
{name: "Alice", age: 30} | to json | save user.json

Pretty print JSON

格式化输出JSON

{name: "Alice", age: 30} | to json -i 2
undefined
{name: "Alice", age: 30} | to json -i 2
undefined

CSV

CSV

nu
undefined
nu
undefined

Read CSV

读取CSV

let data = open data.csv
let data = open data.csv

Convert to CSV

转换为CSV

[{a: 1, b: 2} {a: 3, b: 4}] | to csv
[{a: 1, b: 2} {a: 3, b: 4}] | to csv

Save CSV

保存为CSV

ls | select name size | to csv | save files.csv
undefined
ls | select name size | to csv | save files.csv
undefined

YAML/TOML

YAML/TOML

nu
undefined
nu
undefined

Read YAML

读取YAML

let config = open config.yaml
let config = open config.yaml

Read TOML

读取TOML

let config = open config.toml
let config = open config.toml

Write YAML

写入YAML

{key: "value"} | to yaml | save config.yaml
{key: "value"} | to yaml | save config.yaml

Write TOML

写入TOML

{key: "value"} | to toml | save config.toml
undefined
{key: "value"} | to toml | save config.toml
undefined

Working with Tables

表格操作

nu
undefined
nu
undefined

Create table

创建表格

let users = [ {name: "Alice", age: 30, city: "NYC"} {name: "Bob", age: 25, city: "LA"} {name: "Charlie", age: 35, city: "NYC"} ]
let users = [ {name: "Alice", age: 30, city: "NYC"} {name: "Bob", age: 25, city: "LA"} {name: "Charlie", age: 35, city: "NYC"} ]

Query table

查询表格

$users | where age > 25 $users | where city == "NYC" $users | select name age
$users | where age > 25 $users | where city == "NYC" $users | select name age

Add column

添加列

$users | insert country { "USA" }
$users | insert country { "USA" }

Group and count

分组统计

$users | group-by city | transpose city users
undefined
$users | group-by city | transpose city users
undefined

Modules

模块

Creating Modules

创建模块

nu
undefined
nu
undefined

utils.nu

utils.nu

export def greet [name: string] { print $"Hello, ($name)!" }
export def add [a: int, b: int] { $a + $b }
undefined
export def greet [name: string] { print $"Hello, ($name)!" }
export def add [a: int, b: int] { $a + $b }
undefined

Using Modules

使用模块

nu
undefined
nu
undefined

Import module

导入模块

use utils.nu
use utils.nu

Use exported commands

使用导出的命令

utils greet "Alice" utils add 5 3
utils greet "Alice" utils add 5 3

Import specific commands

导入特定命令

use utils.nu [greet add]
greet "Alice" add 5 3
use utils.nu [greet add]
greet "Alice" add 5 3

Import with alias

导入所有命令

use utils.nu *
undefined
use utils.nu *
undefined

Configuration

配置

Config File Location

配置文件位置

nu
undefined
nu
undefined

View config

查看配置

config nu
config nu

Edit config

编辑配置

config nu | open
config nu | open

Config location

配置文件路径

$nu.config-path
undefined
$nu.config-path
undefined

Common Configurations

常见配置项

nu
undefined
nu
undefined

config.nu

config.nu

$env.config = { show_banner: false
ls: { use_ls_colors: true clickable_links: true }
table: { mode: rounded index_mode: auto }
completions: { quick: true partial: true }
history: { max_size: 10000 sync_on_enter: true file_format: "sqlite" } }
undefined
$env.config = { show_banner: false
ls: { use_ls_colors: true clickable_links: true }
table: { mode: rounded index_mode: auto }
completions: { quick: true partial: true }
history: { max_size: 10000 sync_on_enter: true file_format: "sqlite" } }
undefined

Environment Setup

环境设置

nu
undefined
nu
undefined

env.nu

env.nu

$env.PATH = ($env.PATH | split row (char esep) | append '/custom/bin') $env.EDITOR = "nvim"
$env.PATH = ($env.PATH | split row (char esep) | append '/custom/bin') $env.EDITOR = "nvim"

Load completions

加载补全

use completions/git.nu *
undefined
use completions/git.nu *
undefined

Common Patterns

常见模式

File Processing

文件处理

nu
undefined
nu
undefined

Process all JSON files

处理所有JSON文件

ls *.json | each { |file| let data = open $file.name print $"Processing ($file.name): ($data | length) items" }
ls *.json | each { |file| let data = open $file.name print $"正在处理($file.name): 共($data | length)条数据" }

Batch rename files

批量重命名文件

ls *.txt | each { |file| let new_name = ($file.name | str replace ".txt" ".md") mv $file.name $new_name }
undefined
ls *.txt | each { |file| let new_name = ($file.name | str replace ".txt" ".md") mv $file.name $new_name }
undefined

Data Transformation

数据转换

nu
undefined
nu
undefined

CSV to JSON

CSV转JSON

open data.csv | to json | save data.json
open data.csv | to json | save data.json

Filter and transform

过滤并转换

open users.json | where active == true | select name email | to csv | save active_users.csv
open users.json | where active == true | select name email | to csv | save active_users.csv

Merge data

合并数据

let users = open users.json let orders = open orders.json $users | merge $orders
undefined
let users = open users.json let orders = open orders.json $users | merge $orders
undefined

HTTP Requests

HTTP请求

nu
undefined
nu
undefined

GET request

GET请求

POST request

POST请求

http post https://api.example.com/users { name: "Alice" email: "alice@example.com" }
http post https://api.example.com/users { name: "Alice" email: "alice@example.com" }

With headers

带请求头

http get -H [Authorization "Bearer token"] https://api.example.com/data
undefined
http get -H [Authorization "Bearer token"] https://api.example.com/data
undefined

System Commands

系统命令

nu
undefined
nu
undefined

Run external command

执行外部命令

^ls -la
^ls -la

Capture output

捕获输出

let output = (^git status)
let output = (^git status)

Check if command exists

检查命令是否存在

which git
which git

Get command path

获取命令路径

which git | get path
undefined
which git | get path
undefined

Error Handling

错误处理

Try-Catch

Try-Catch

nu
undefined
nu
undefined

Try expression

Try表达式

try { open missing.txt } catch { print "File not found" }
try { open missing.txt } catch { print "文件不存在" }

With error value

捕获错误信息

try { open missing.txt } catch { |err| print $"Error: ($err)" }
undefined
try { open missing.txt } catch { |err| print $"错误信息: ($err)" }
undefined

Null Handling

空值处理

nu
undefined
nu
undefined

Default value

默认值

let value = ($env.MY_VAR? | default "default_value")
let value = ($env.MY_VAR? | default "默认值")

Null propagation

空值传播

let length = ($value | get name? | str length)
undefined
let length = ($value | get name? | str length)
undefined

Scripting

脚本编写

Script Files

脚本文件

nu
#!/usr/bin/env nu
nu
#!/usr/bin/env nu

Script: process_logs.nu

脚本: process_logs.nu

Description: Process log files and generate report

描述: 处理日志文件并生成报告

def main [log_dir: path] { let errors = ( ls $"($log_dir)/*.log" | each { |file| open $file.name | lines } | flatten | where $it =~ "ERROR" )
print $"Found ($errors | length) errors" $errors | save error_report.txt }

Make executable:
```bash
chmod +x process_logs.nu
./process_logs.nu /var/log
def main [log_dir: path] { let errors = ( ls $"($log_dir)/*.log" | each { |file| open $file.name | lines } | flatten | where $it =~ "ERROR" )
print $"发现($errors | length)条错误" $errors | save error_report.txt }

设置可执行权限:
```bash
chmod +x process_logs.nu
./process_logs.nu /var/log

Script Parameters

脚本参数

nu
undefined
nu
undefined

With parameters

带参数的脚本

def main [ input: path --output (-o): path = "output.txt" --verbose (-v) ] { if $verbose { print $"Processing ($input)..." }
let data = open $input $data | save $output
if $verbose { print "Done!" } }
undefined
def main [ input: path --output (-o): path = "output.txt" --verbose (-v) ] { if $verbose { print $"正在处理($input)..." }
let data = open $input $data | save $output
if $verbose { print "处理完成!" } }
undefined

Comparison with Bash

与Bash的对比

Common Operations

常见操作对比

bash
undefined
bash
undefined

Bash

Bash

find . -name "*.txt" | wc -l
find . -name "*.txt" | wc -l

Nushell

Nushell

ls **/*.txt | length

```bash
ls **/*.txt | length

```bash

Bash

Bash

cat file.json | jq '.users[] | select(.age > 25) | .name'
cat file.json | jq '.users[] | select(.age > 25) | .name'

Nushell

Nushell

open file.json | get users | where age > 25 | get name

```bash
open file.json | get users | where age > 25 | get name

```bash

Bash

Bash

for file in *.txt; do mv "$file" "${file%.txt}.md" done
for file in *.txt; do mv "$file" "${file%.txt}.md" done

Nushell

Nushell

ls *.txt | each { |f| mv $f.name ($f.name | str replace ".txt" ".md") }
undefined
ls *.txt | each { |f| mv $f.name ($f.name | str replace ".txt" ".md") }
undefined

Best Practices

最佳实践

  • Use structured data: Leverage Nu's strength in handling structured data
  • Pipeline composition: Build complex operations from simple pipeline stages
  • Type annotations: Add types to custom command parameters for clarity
  • Error handling: Use try-catch for operations that might fail
  • Modules for reuse: Organize reusable commands in modules
  • Configuration: Customize Nu to fit your workflow
  • External commands: Use
    ^
    prefix when calling external commands explicitly
  • 使用结构化数据:充分利用Nu处理结构化数据的优势
  • 管道组合:通过简单的管道步骤构建复杂操作
  • 类型注解:为自定义命令参数添加类型注解以提升可读性
  • 错误处理:对可能失败的操作使用try-catch
  • 模块复用:将可复用的命令组织到模块中
  • 个性化配置:根据工作流自定义Nu的配置
  • 外部命令:调用外部命令时显式使用
    ^
    前缀

Common Pitfalls

常见陷阱

String vs Bare Words

字符串与裸词

nu
undefined
nu
undefined

Bare word (interpreted as string in some contexts)

裸词(部分上下文会被解析为字符串)

echo hello
echo hello

Explicit string (clearer)

显式字符串(更清晰)

echo "hello"
undefined
echo "hello"
undefined

External Commands

外部命令

nu
undefined
nu
undefined

Wrong - Nu tries to parse as Nu command

错误写法 - Nu会尝试解析为Nu命令

ls -la
ls -la

Right - Explicitly call external command

正确写法 - 显式调用外部命令

^ls -la
undefined
^ls -la
undefined

Variable Scope

变量作用域

nu
undefined
nu
undefined

Variables are scoped to blocks

变量作用域限于代码块内

if true { let x = 5 }
if true { let x = 5 }

$x not available here

此处无法访问$x

Use mut outside for wider scope

使用mut定义全局作用域变量

mut x = 0 if true { $x = 5 } print $x # Works
undefined
mut x = 0 if true { $x = 5 } print $x # 可以正常访问
undefined

Key Principles

核心原则

  • Structured data first: Think in terms of tables and records, not text
  • Pipeline composition: Chain simple operations to build complex workflows
  • Type safety: Leverage Nu's type system for reliable scripts
  • Cross-platform: Write scripts that work on all platforms
  • Interactive and scriptable: Same syntax works in REPL and scripts
  • Clear errors: Nu provides helpful error messages for debugging
  • 结构化数据优先:以表格和记录的思路思考,而非纯文本
  • 管道组合:通过链式简单操作构建复杂工作流
  • 类型安全:利用Nu的类型系统编写可靠脚本
  • 跨平台:编写可在所有平台运行的脚本
  • 交互与脚本通用:REPL与脚本使用相同语法
  • 清晰的错误提示:Nu提供便于调试的错误信息