コンテンツにスキップ

Nushell

コマンド出力をテーブルとして扱い、型付きデータによるパイプライン、フィルタリング、クロスプラットフォームスクリプティングをサポートするモダンな構造化データシェル。

コマンド説明
brew install nushellmacOSにHomebrewでインストール
cargo install nucrates.ioからインストール
winget install nushellWindowsにwingetでインストール
sudo apt install nushellDebian/Ubuntuにインストール
pacman -S nushellArch Linuxにインストール
nix-env -i nushellNixOSにインストール
nuNushellを起動
nu --versionインストール済みバージョンを表示
nu -c "ls"単一コマンドを実行して終了
nu script.nuNushellスクリプトファイルを実行
chsh -s /usr/bin/nuNushellをデフォルトシェルに設定
コマンド説明
sysシステム情報の全体を表示
sys hostホスト詳細を表示(名前、OS、カーネル)
sys memメモリ使用量を表示
sys cpuCPU情報を表示
sys disksディスク使用量を表示
sys netネットワークインターフェースを表示
sys temp温度センサーを表示
date now現在の日時を表示
date now | format date "%Y-%m-%d"現在の日付をフォーマット
$nu.home-pathホームディレクトリのパスを表示
$nu.os-infoOS詳細を表示
コマンド説明
lsファイルを構造化テーブルとして一覧表示
ls -l詳細付きの長い一覧
ls -a隠しファイルを表示
ls **/*.rsRustファイルの再帰的glob
ls | where size > 1mb1MBより大きいファイルをフィルタ
ls | where type == dirディレクトリのみフィルタ
ls | sort-by modified -r更新日時でソート(新しい順)
ls | sort-by size -rサイズ降順でソート
ls | get nameファイル名カラムのみ取得
コマンド説明
psプロセスをテーブルとして一覧表示
ps | where cpu > 10CPU使用率10%超のプロセスを検索
ps | where name =~ "node"名前パターンでプロセスを検索
ps | sort-by mem -r | first 10メモリ使用量上位10プロセス
ps | where pid == 1234PIDでプロセスを検索
コマンド説明
help一般的なヘルプを表示
help commands利用可能な全コマンドを一覧表示
help ls特定コマンドのヘルプを表示
help operators利用可能な演算子を一覧表示
help escapes文字列エスケープシーケンスを表示
コマンド説明
ls | select name size特定カラムを選択
ls | reject modified特定カラムを除外
ls | rename filename filesizeカラム名を変更
ls | first 5最初の5行を取得
ls | last 3最後の3行を取得
ls | skip 10最初の10行をスキップ
ls | length行数をカウント
ls | reverse行の順序を逆にする
ls | shuffle行の順序をランダム化
ls | flattenネストされたテーブルをフラット化
ls | columnsカラム名を一覧表示
コマンド説明
ls | where size > 1mb比較でフィルタ
ls | where name =~ "test"正規表現マッチでフィルタ
ls | where name starts-with "src"プレフィックスでフィルタ
ls | where name ends-with ".md"サフィックスでフィルタ
ls | where type in ["file" "dir"]値リストでフィルタ
ls | sort-by size -r降順ソート
ls | sort-by name -i大文字小文字を区別しないソート
ls | uniq-by typeカラムで重複を除去
ls | group-by typeカラム値で行をグループ化
コマンド説明
ls | each { |it| $it.name }各行を変換
ls | par-each { |it| $it.name }並列で変換
ls | update size { |it| $it.size / 1kb }カラム値を更新
ls | insert label { |it| $it.name + "-file" }新しいカラムを追加
ls | reduce -f 0 { |it, acc| $acc + $it.size }値を累積
ls | enumerateインデックスカラムを追加
ls | window 33行のスライディングウィンドウ
ls | zip [1 2 3]別のリストとzip
ls | transpose行と列を入れ替え
コマンド説明
42整数
3.14浮動小数点数
"hello"文字列
true / falseブール値
nullNull値
2024-01-15日付
5sec / 3min / 2hr期間
1kb / 5mb / 2gbファイルサイズ
0b1010バイナリリテラル
0xff16進数リテラル
コマンド説明
[1 2 3]リスト
[1 2 3] | append 4リストに追加
[1 2 3] | prepend 0リストの先頭に追加
{name: "Alice", age: 30}レコード
{a: 1} | merge {b: 2}レコードをマージ
[[name age]; ["Alice" 30] ["Bob" 25]]テーブルリテラル
0..9範囲(0から9)
0..<9排他的範囲(0から8)
0..2..10ステップ付き範囲(0, 2, 4, 6, 8, 10)
コマンド説明
"42" | into int文字列を整数に変換
"3.14" | into float文字列を浮動小数点数に変換
42 | into string数値を文字列に変換
"true" | into bool文字列をブール値に変換
"2024-01-15" | into datetime文字列を日時に変換
1024 | into filesize数値をファイルサイズに変換
5 | into duration --unit sec数値を期間に変換
42 | into binary数値をバイナリに変換
[1 2 3] | into recordリストをレコードに変換
{a: 1} | into recordレコードに変換
コマンド説明
open data.jsonJSONファイルを開いてパース
open data.csvCSVファイルを開いてパース
open data.yamlYAMLファイルを開いてパース
open data.tomlTOMLファイルを開いてパース
open data.xmlXMLファイルを開いてパース
open data.tsvTSVファイルを開いてパース
open data.sqliteSQLiteデータベースを開く
open file.txtプレーンテキストとして開く
open data.json | get users開いてデータ内をナビゲート
コマンド説明
"hello" | save hello.txt文字列をファイルに保存
ls | save files.jsonテーブルをJSONとして保存
ls | save files.csvテーブルをCSVとして保存
ls | save files.yamlテーブルをYAMLとして保存
open data.json | to csvJSONをCSVに変換
open data.csv | to jsonCSVをJSONに変換
open data.json | save data.yamlフォーマット間で変換
open data.csv | save -f data.csv既存ファイルを強制上書き
"line1\nline2" | save -a log.txtファイルに追記
コマンド説明
open file.txt | linesファイルを行に分割
open file.txt | lines | lengthファイルの行数をカウント
open file.csv | where status == "active"CSVの行をフィルタ
open file.json | select name emailJSONからフィールドを選択
open file.json | to yaml | save file.yamlJSONをYAMLに変換
glob "**/*.md" | each { |f| open $f }マッチする全ファイルを開く
コマンド説明
"hello world" | str upcase大文字に変換
"HELLO" | str downcase小文字に変換
"hello" | str capitalize最初の文字を大文字に
" hello " | str trim空白をトリム
"hello" | str trim --char "h"特定の文字をトリム
"hello" | str reverse文字列を反転
コマンド説明
"hello world" | str replace "world" "nu"最初の出現を置換
"aabaa" | str replace -a "a" "x"全ての出現を置換
"hello world" | str replace -r '\w+' 'word'正規表現で置換
"hello world" | str contains "world"文字列が含まれるか確認
"hello world" | str starts-with "hello"プレフィックスを確認
"hello world" | str ends-with "world"サフィックスを確認
"hello world" | str index-of "world"部分文字列の位置を検索
コマンド説明
"hello world" | split row " "デリミタで分割
"a,b,c" | split row ","CSV形式の文字列を分割
"hello" | split chars文字に分割
["hello" "world"] | str join " "リストを文字列に結合
["a" "b" "c"] | str join ","カンマで結合
"hello" | str length文字列の長さを取得
"hello world" | str substring 0..5部分文字列を抽出
# 基本的な補間
let name = "World"
$"Hello, ($name)!"

# 式の補間
$"Total: (1 + 2 + 3)"

# 複数行文字列
$"Line 1
Line 2
Line 3"

# 生文字列(エスケープなし)
r#'C:\Users\path'#
コマンド説明
def greet [name: string] { $"Hello, ($name)!" }基本的なカスタムコマンド
def add [a: int, b: int] -> int { $a + $b }型アノテーション付きコマンド
def greet [name = "World"] { ... }デフォルトパラメータ付きコマンド
def "git branches" [] { git branch | lines }サブコマンドスタイルの名前
def --wrapped cmd [...rest] { ... }追加の引数を受け入れる
コマンド説明
let x = 42不変変数
mut x = 0; $x = $x + 1可変変数
const PI = 3.14159コンパイル時定数
if $x > 0 { "pos" } else { "neg" }条件式
match $x { 1 => "one", 2 => "two", _ => "other" }パターンマッチング
for item in [1 2 3] { print $item }forループ
while $x < 10 { $x = $x + 1 }whileループ
loop { if $x > 10 { break }; $x += 1 }break付き無限ループ
try { risky_op } catch { "failed" }エラーハンドリング
# フラグパラメータ付き関数
def greet [
  name: string       # 挨拶する名前
  --excited (-e)     # 感嘆符を使用
] {
  if $excited {
    $"Hello, ($name)!"
  } else {
    $"Hello, ($name)."
  }
}

# 可変長パラメータ付き関数
def sum [...nums: int] -> int {
  $nums | math sum
}

# パイプライン入力関数
def double-all [] {
  each { |x| $x * 2 }
}
# 使い方: [1 2 3] | double-all
コマンド説明
[1 2 3 4 5] | math sum値の合計
[1 2 3 4 5] | math avg値の平均
[1 2 3 4 5] | math min最小値
[1 2 3 4 5] | math max最大値
[1 2 3 4 5] | math median中央値
[1 2 3 4 5] | math stddev標準偏差
[1 2 3 4 5] | math variance分散
[1 2 3] | math product値の積
10 | math abs絶対値
10 | math sqrt平方根
2 | math round -p 2精度を指定して丸め
10 | math log 2底2の対数
コマンド説明
http get https://api.example.com/dataGETリクエスト
http post https://api.example.com/data {name: "test"}JSONでPOSTリクエスト
http put https://api.example.com/data/1 {name: "updated"}PUTリクエスト
http delete https://api.example.com/data/1DELETEリクエスト
http get url --headers [Accept application/json]カスタムヘッダー付きGET
http get url | get dataGETしてフィールドを抽出
port 8080ポートが使用中か確認
# JSON APIの取得と処理
let users = (http get "https://jsonplaceholder.typicode.com/users")
$users | select name email | first 5

# ヘッダーとボディ付きPOST
http post "https://api.example.com/items" {
  name: "New Item"
  price: 29.99
} --headers [Authorization $"Bearer ($env.API_TOKEN)"]
コマンド説明
$nu.config-path設定ファイルのパスを表示
$nu.env-path環境設定ファイルのパスを表示
$nu.default-config-dir設定ディレクトリを表示
config nuエディタで設定を開く
config envエディタで環境設定を開く
コマンド説明
$env.config.show_banner = false起動バナーを無効化
$env.config.buffer_editor = "vim"Ctrl+O用のエディタを設定
$env.config.history.file_format = "sqlite"SQLite履歴を使用
$env.config.history.max_size = 100_000最大履歴エントリ数を設定
$env.config.completions.external.enable = true外部補完を有効化
$env.config.cursor_shape.emacs = "line"カーソルの形状を設定
$env.config.footer_mode = "25"大きなテーブルのフッターを表示
$env.config.table.mode = "rounded"テーブルの枠線スタイルを設定
コマンド説明
$env.PATH = ($env.PATH | prepend "/usr/local/bin")PATHに追加
$env.PATH = ($env.PATH | append "~/.local/bin")PATHの末尾に追加
$env.EDITOR = "vim"環境変数を設定
alias ll = ls -lコマンドエイリアスを作成
source ~/.config/nushell/custom.nu追加設定を読み込み
# env.nu — 環境設定
$env.PATH = ($env.PATH | split row (char esep)
  | prepend "/usr/local/bin"
  | prepend ($env.HOME | path join ".cargo" "bin")
  | append ($env.HOME | path join "go" "bin")
)

$env.EDITOR = "nvim"
$env.VISUAL = "nvim"
$env.PAGER = "less"
# config.nu — シェル設定
$env.config = {
  show_banner: false
  buffer_editor: "nvim"
  table: {
    mode: rounded
    index_mode: auto
    trim: {
      methodology: wrapping
      wrapping_try_keep_words: true
    }
  }
  history: {
    file_format: "sqlite"
    max_size: 100_000
    sync_on_enter: true
    isolation: false
  }
  completions: {
    case_sensitive: false
    quick: true
    partial: true
    algorithm: "prefix"
    external: {
      enable: true
      max_results: 100
    }
  }
}
コマンド説明
module greet { export def hello [] { "hi" } }モジュールをインラインで定義
use greet helloモジュールからコマンドをインポート
use greet *モジュールから全てをインポート
use utils.nuファイルモジュールからインポート
overlay use spamオーバーレイを有効化
overlay hide spamオーバーレイを無効化
overlay listアクティブなオーバーレイを一覧表示
# ファイル: utils.nu
export def "str kebab" [] {
  $in | str downcase | str replace -a " " "-"
}

export def "str title" [] {
  $in | split row " "
  | each { |w| $w | str capitalize }
  | str join " "
}

# 使い方:
# use utils.nu
# "Hello World" | str kebab    # "hello-world"
# "hello world" | str title    # "Hello World"
コマンド説明
open data.dbSQLiteデータベースを開く
open data.db | query db "SELECT * FROM users"SQLクエリを実行
open data.db | query db "SELECT * FROM users WHERE age > 30"フィルタ付きクエリ
open data.db | schemaデータベーススキーマを表示
[[name age]; ["Alice" 30]] | into sqlite data.dbテーブルからSQLiteを作成
ls | into sqlite -t files data.dbテーブルをSQLiteに保存
コマンド説明
plugin listインストール済みプラグインを一覧表示
plugin add /path/to/pluginプラグインを登録
plugin rm plugin_nameプラグインを削除
plugin use plugin_nameプラグインを読み込み
cargo install nu_plugin_formatsformatsプラグインをインストール
cargo install nu_plugin_queryqueryプラグインをインストール
cargo install nu_plugin_gstatgit statusプラグインをインストール
  1. 構造化データを活用する — Nushellは生の文字列ではなく、テーブルとレコードを使って作業する時に真価を発揮します。grepawkの代わりにselectwheresort-byでパイプ処理しましょう。

  2. 関数パラメータに型を付ける — カスタムコマンドに型アノテーション(name: stringcount: int)を追加して、エラーを早期に検出し、より良い自動補完を有効にしましょう。

  3. 不変変数を優先する — デフォルトでletを使い、本当にミューテーションが必要な場合にのみmutを使用しましょう。スクリプト内の意図しない状態変更を防ぎます。

  4. SQLite履歴を使用する$env.config.history.file_format = "sqlite"を設定して、より高速な検索、より良い破損耐性、より豊富なメタデータを得ましょう。

  5. パフォーマンスのためにpar-eachを活用する — 多くのアイテムを独立して処理する場合、par-eachは並列スレッドで実行され、eachよりも大幅に高速になります。

  6. 再利用可能なコードにはモジュールを使用する — カスタムコマンドを.nuモジュールファイルに整理し、sourceではなくuseで読み込みましょう。モジュールは適切な名前空間とエクスポートを持っています。

  7. 型変換にはintoを使用する — 信頼性の高いスクリプトのために、暗黙的な型強制に頼らず、常に明示的な型変換(into intinto stringなど)を使用しましょう。

  8. 補完を設定する — 外部補完とcarapaceを有効にして、全てのCLIツールでシェル補完をサポートしましょう。

  9. 文字列補間を使用する+による文字列連結よりも$"Hello, ($name)!"を優先して、よりクリーンで読みやすいコードにしましょう。

  10. try/catchでエラーを処理する — 失敗する可能性のある操作(ファイルアクセス、HTTP、パース)をtry { } catch { }ブロックで囲んで、堅牢なスクリプトにしましょう。

  11. describeでテストする — 開発やデバッグ中にexpression | describeを使って、あらゆる値の型を検査しましょう。

  12. クロージャを一貫して使用する — Nushellのクロージャは{ |params| body }構文を使います。明確さのために、単一パラメータでも常にパイプ文字を含めましょう。