nushell
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNushell - 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
undefinedbash
undefinedmacOS
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/
undefinedundefinedBasic Concepts
基础概念
Everything is Data
一切皆数据
Unlike traditional shells where everything is text, Nu works with structured data:
nu
undefined与传统Shell中所有内容都是文本不同,Nu以结构化数据为核心:
nu
undefinedTraditional shell (text output)
传统Shell(文本输出)
ls | grep ".txt"
ls | grep ".txt"
Nushell (structured data)
Nushell(结构化数据)
ls | where name =~ ".txt"
undefinedls | where name =~ ".txt"
undefinedPipeline Philosophy
管道设计理念
Data flows through pipelines as structured tables/records:
nu
undefined数据以结构化表格/记录的形式在管道中流转:
nu
undefinedEach command outputs structured data
每个命令输出结构化数据
ls | where size > 1kb | sort-by modified | reverse
undefinedls | where size > 1kb | sort-by modified | reverse
undefinedData Types
数据类型
Basic Types
基础类型
nu
undefinednu
undefinedIntegers
整数
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
undefinednull
undefinedCollections
集合类型
nu
undefinednu
undefinedLists
列表
[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}
]
undefinedRanges
范围类型
nu
undefinednu
undefinedNumber ranges
数值范围
1..10
1..2..10 # Step by 2
1..10
1..2..10 # 步长为2
Use in commands
在命令中使用
1..5 | each { |i| $i * 2 }
undefined1..5 | each { |i| $i * 2 }
undefinedWorking with Files and Directories
文件与目录操作
Navigation
导航
nu
undefinednu
undefinedChange 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$"
undefinedls | where type == file
ls | where size > 1mb
ls | where name =~ ".txt$"
undefinedFile Operations
文件操作
nu
undefinednu
undefinedCreate 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
undefinedmkdir new-dir
undefinedFile Content
文件内容处理
nu
undefinednu
undefinedRead 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
undefinedPipeline Operations
管道操作
Filtering
过滤
nu
undefinednu
undefinedFilter 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
undefinedls | where size > 1kb and type == file
undefinedSelecting Columns
选择列
nu
undefinednu
undefinedSelect specific columns
选择特定列
ls | select name size
ls | select name size
Rename columns
重命名列
ls | select name size | rename file bytes
undefinedls | select name size | rename file bytes
undefinedSorting
排序
nu
undefinednu
undefinedSort 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
undefinedls | sort-by type size
undefinedTransforming Data
数据转换
nu
undefinednu
undefinedMap 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 }
undefinedls | upsert type_upper { |row| $row.type | str upcase }
undefinedAggregation
聚合
nu
undefinednu
undefinedCount 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
undefinedls | group-by type
undefinedVariables
变量
Variable Assignment
变量赋值
nu
undefinednu
undefinedLet (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
undefinedmut counter = 0
$counter = $counter + 1
undefinedUsing Variables
变量使用
nu
undefinednu
undefinedReference with $
使用$引用变量
let name = "Alice"
print $"Hello, ($name)!"
let name = "Alice"
print $"Hello, ($name)!"
In pipelines
在管道中使用
let threshold = 1mb
ls | where size > $threshold
undefinedlet threshold = 1mb
ls | where size > $threshold
undefinedEnvironment Variables
环境变量
nu
undefinednu
undefinedGet 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" }
undefinedload-env { API_KEY: "secret" }
undefinedString Operations
字符串操作
String Interpolation
字符串插值
nu
undefinednu
undefinedString interpolation with ()
使用()进行字符串插值
let name = "Alice"
print $"Hello, ($name)!"
let name = "Alice"
print $"Hello, ($name)!"
With expressions
结合表达式
let x = 5
print $"Result: (5 * $x)"
undefinedlet x = 5
print $"Result: (5 * $x)"
undefinedString Methods
字符串方法
nu
undefinednu
undefinedCase 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 ","
undefinedConditionals
条件判断
If Expressions
If表达式
nu
undefinednu
undefinedIf-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" }
undefinedlet status = if $is_active { "活跃" } else { "非活跃" }
undefinedMatch (Pattern Matching)
Match(模式匹配)
nu
undefinednu
undefinedMatch expression
Match表达式
match $value {
1 => "one"
2 => "two"
_ => "other"
}
match $value {
1 => "一"
2 => "二"
_ => "其他"
}
With conditions
带条件的匹配
match $age {
0..17 => "minor"
18..64 => "adult"
_ => "senior"
}
undefinedmatch $age {
0..17 => "未成年人"
18..64 => "成年人"
_ => "老年人"
}
undefinedLoops
循环
For Loop
For循环
nu
undefinednu
undefinedLoop 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
}
undefinedfor file in (ls | where type == file) {
print $file.name
}
undefinedWhile Loop
While循环
nu
undefinednu
undefinedWhile loop
While循环
mut i = 0
while $i < 5 {
print $i
$i = $i + 1
}
undefinedmut i = 0
while $i < 5 {
print $i
$i = $i + 1
}
undefinedEach (Functional)
Each(函数式遍历)
nu
undefinednu
undefinedTransform 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)"
}
undefinedCustom Commands
自定义命令
Defining Commands
定义命令
nu
undefinednu
undefinedSimple 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)!"
}
undefineddef greet [name: string = "World"] {
print $"Hello, ($name)!"
}
undefinedCommand Parameters
命令参数
nu
undefinednu
undefinedRequired 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
undefinedgreet "Alice"
greet "Bob" --loud
greet "Charlie" --repeat 3
undefinedPipeline Commands
管道命令
nu
undefinednu
undefinedAccept 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
undefineddef double [] {
each { |value| $value * 2 }
}
[1 2 3] | double
undefinedWorking with Structured Data
结构化数据处理
JSON
JSON
nu
undefinednu
undefinedRead 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
undefinedCSV
CSV
nu
undefinednu
undefinedRead 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
undefinedls | select name size | to csv | save files.csv
undefinedYAML/TOML
YAML/TOML
nu
undefinednu
undefinedRead 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
undefinedWorking with Tables
表格操作
nu
undefinednu
undefinedCreate 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
undefinedModules
模块
Creating Modules
创建模块
nu
undefinednu
undefinedutils.nu
utils.nu
export def greet [name: string] {
print $"Hello, ($name)!"
}
export def add [a: int, b: int] {
$a + $b
}
undefinedexport def greet [name: string] {
print $"Hello, ($name)!"
}
export def add [a: int, b: int] {
$a + $b
}
undefinedUsing Modules
使用模块
nu
undefinednu
undefinedImport 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 *
undefineduse utils.nu *
undefinedConfiguration
配置
Config File Location
配置文件位置
nu
undefinednu
undefinedView config
查看配置
config nu
config nu
Edit config
编辑配置
config nu | open
config nu | open
Config location
配置文件路径
$nu.config-path
undefined$nu.config-path
undefinedCommon Configurations
常见配置项
nu
undefinednu
undefinedconfig.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"
}
}
undefinedEnvironment Setup
环境设置
nu
undefinednu
undefinedenv.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 *
undefineduse completions/git.nu *
undefinedCommon Patterns
常见模式
File Processing
文件处理
nu
undefinednu
undefinedProcess 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
}
undefinedls *.txt | each { |file|
let new_name = ($file.name | str replace ".txt" ".md")
mv $file.name $new_name
}
undefinedData Transformation
数据转换
nu
undefinednu
undefinedCSV 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
undefinedlet users = open users.json
let orders = open orders.json
$users | merge $orders
undefinedHTTP Requests
HTTP请求
nu
undefinednu
undefinedGET request
GET请求
http get https://api.example.com/users
http get https://api.example.com/users
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
undefinedhttp get -H [Authorization "Bearer token"] https://api.example.com/data
undefinedSystem Commands
系统命令
nu
undefinednu
undefinedRun 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
undefinedwhich git | get path
undefinedError Handling
错误处理
Try-Catch
Try-Catch
nu
undefinednu
undefinedTry 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)"
}
undefinedtry {
open missing.txt
} catch { |err|
print $"错误信息: ($err)"
}
undefinedNull Handling
空值处理
nu
undefinednu
undefinedDefault value
默认值
let value = ($env.MY_VAR? | default "default_value")
let value = ($env.MY_VAR? | default "默认值")
Null propagation
空值传播
let length = ($value | get name? | str length)
undefinedlet length = ($value | get name? | str length)
undefinedScripting
脚本编写
Script Files
脚本文件
nu
#!/usr/bin/env nunu
#!/usr/bin/env nuScript: 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/logdef 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/logScript Parameters
脚本参数
nu
undefinednu
undefinedWith 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!"
}
}
undefineddef main [
input: path
--output (-o): path = "output.txt"
--verbose (-v)
] {
if $verbose {
print $"正在处理($input)..."
}
let data = open $input
$data | save $output
if $verbose {
print "处理完成!"
}
}
undefinedComparison with Bash
与Bash的对比
Common Operations
常见操作对比
bash
undefinedbash
undefinedBash
Bash
find . -name "*.txt" | wc -l
find . -name "*.txt" | wc -l
Nushell
Nushell
ls **/*.txt | length
```bashls **/*.txt | length
```bashBash
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
```bashopen file.json | get users | where age > 25 | get name
```bashBash
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") }
undefinedls *.txt | each { |f| mv $f.name ($f.name | str replace ".txt" ".md") }
undefinedBest 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
undefinednu
undefinedBare word (interpreted as string in some contexts)
裸词(部分上下文会被解析为字符串)
echo hello
echo hello
Explicit string (clearer)
显式字符串(更清晰)
echo "hello"
undefinedecho "hello"
undefinedExternal Commands
外部命令
nu
undefinednu
undefinedWrong - Nu tries to parse as Nu command
错误写法 - Nu会尝试解析为Nu命令
ls -la
ls -la
Right - Explicitly call external command
正确写法 - 显式调用外部命令
^ls -la
undefined^ls -la
undefinedVariable Scope
变量作用域
nu
undefinednu
undefinedVariables 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
undefinedmut x = 0
if true {
$x = 5
}
print $x # 可以正常访问
undefinedKey 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提供便于调试的错误信息