### Rustup Installation Options Source: https://www.nushell.sh/book/installation.html Example output from rustup showing default installation options for the Rust toolchain. Press '1' to proceed with the default installation. ```shell Current installation options: default host triple: x86_64-unknown-linux-gnu default toolchain: stable profile: default modify PATH variable: yes 1) Proceed with installation (default) 2) Customize installation 3) Cancel installation ``` -------------------------------- ### Install Plugin from Local Repository Source: https://www.nushell.sh/book/plugins.html Install a plugin by providing the path to its local repository. This is useful when developing or installing plugins not yet published. ```bash cargo install --path . --locked ``` -------------------------------- ### Install Nu with Winget (User Scope) Source: https://www.nushell.sh/book/installation.html Install Nushell for the current user on a Windows machine using Winget. ```shell winget install nushell ``` -------------------------------- ### Install Nu with Winget (Machine Scope) Source: https://www.nushell.sh/book/installation.html Install Nushell for all users on a Windows machine using Winget. ```shell winget install nushell --scope machine ``` -------------------------------- ### Iterate and Change Directory within a Block Source: https://www.nushell.sh/book/thinking_in_nu.html This example demonstrates how to iterate through subdirectories, change into each one, and execute a command. Environment changes like `cd` are scoped to the block, ensuring each iteration starts from the correct directory. ```nushell ls | each { |row| cd $row.name make } ``` -------------------------------- ### List Installed Plugins Source: https://www.nushell.sh/book/plugins.html Display a list of all plugins currently installed and recognized by Nushell. ```bash plugin list ``` -------------------------------- ### Example XDG_CONFIG_HOME Setting Source: https://www.nushell.sh/book/configuration.html Illustrates the correct way to set the $env.XDG_CONFIG_HOME environment variable for Nushell. ```nushell /users/username/dotfiles ``` -------------------------------- ### Install Plugin from Crates.io Source: https://www.nushell.sh/book/plugins.html Use this command to install a plugin published on crates.io. Ensure the plugin name follows the `nu_plugin_` convention. ```bash cargo install nu_plugin_ --locked ``` -------------------------------- ### Install Nu with Scoop Source: https://www.nushell.sh/book/installation.html Install Nushell on Windows using the Scoop package manager. ```shell scoop install nu ``` -------------------------------- ### Install All Default Core Plugins using Cargo Source: https://www.nushell.sh/book/plugins.html Install all default Nushell core plugins using Cargo. This command iterates through a list of plugin names and installs them individually. ```nushell [ nu_plugin_inc nu_plugin_polars nu_plugin_gstat nu_plugin_formats nu_plugin_query ] | each { cargo install $in --locked } | ignore ``` -------------------------------- ### Send executehostcommand event Source: https://www.nushell.sh/book/line_editor.html Example of configuring a 'send' event for 'executehostcommand', including the command to be executed. ```yaml ... event: { send: executehostcommand cmd: "cd ~" } ... ``` -------------------------------- ### Sourcing a File from Default Config Directory Source: https://www.nushell.sh/book/configuration.html Example of sourcing a file using the $nu.default-config-dir constant, which is known at parse-time. ```nushell source ($nu.default-config-dir | path join "myfile.nu") ``` -------------------------------- ### List All Commands from Installed Plugins Source: https://www.nushell.sh/book/plugins.html Use this command to see all available commands provided by installed plugins. Filter by type 'plugin' to specifically list plugin commands. ```nushell scope commands | where type == "plugin" ``` -------------------------------- ### Import and use a simple module Source: https://www.nushell.sh/book/modules/creating_modules.html Import all definitions from a module using 'use *' and then use the exported commands. This example imports and uses the 'increment' command. ```nu use inc.nu * 5 | increment # => 6 ``` -------------------------------- ### Install Nu with npm Source: https://www.nushell.sh/book/installation.html Install Nushell globally using npm. Note that Nu plugins are not included with this installation method. ```shell npm install -g nushell ``` -------------------------------- ### Install Build Dependencies for Debian/Ubuntu Source: https://www.nushell.sh/book/installation.html Install necessary packages for building Nushell on Debian or Ubuntu systems. ```shell apt install pkg-config libssl-dev build-essential ``` -------------------------------- ### Add Nushell APT Repository and Install Source: https://www.nushell.sh/book/installation.html Configure the APT package manager for Debian/Ubuntu systems to include the Nushell repository and install Nushell. ```shell wget -qO- https://apt.fury.io/nushell/gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/fury-nushell.gpg echo "deb [signed-by=/etc/apt/keyrings/fury-nushell.gpg] https://apt.fury.io/nushell/ /" | sudo tee /etc/apt/sources.list.d/fury-nushell.list sudo apt update sudo apt install nushell ``` -------------------------------- ### List Available Table Border Modes Source: https://www.nushell.sh/book/coloring_and_theming.html List the available options for the `$env.config.table.mode` setting. The output is paginated, and this example shows how to view the first 5 options. ```nu table --list | first 5 ``` -------------------------------- ### Initialize oh-my-posh Prompt in Nushell Source: https://www.nushell.sh/book/3rdpartyprompts.html Generates the .oh-my-posh.nu configuration file. Ensure oh-my-posh is installed and a theme is specified using the --config flag if not using the default. ```nu # Generate the .oh-my-posh.nu file oh-my-posh init nu --config ~/.poshthemes/M365Princess.omp.json # Initialize oh-my-posh.nu at shell startup by adding this line in your config.nu file source ~/.oh-my-posh.nu ``` -------------------------------- ### Add Nushell DNF Repository and Install Source: https://www.nushell.sh/book/installation.html Configure the DNF package manager for RedHat/Fedora/Rocky Linux systems to include the Nushell repository and install Nushell. ```shell echo "[gemfury-nushell] name=Gemfury Nushell Repo baseurl=https://yum.fury.io/nushell/ enabled=1 gpgcheck=0 gpgkey=https://yum.fury.io/nushell/gpg.key" | sudo tee /etc/yum.repos.d/fury-nushell.repo sudo dnf install -y nushell ``` -------------------------------- ### Run Nushell REPL Source: https://www.nushell.sh/book/configuration.html Starts the Nushell interactive REPL. By default, it loads the standard library and user configuration files. ```bash nu ``` -------------------------------- ### Set Buffer Editor to VS Code Source: https://www.nushell.sh/book/configuration.html A specific example of setting the `buffer_editor` configuration to use Visual Studio Code. ```nu $env.config.buffer_editor = 'code' ``` -------------------------------- ### History Menu Quick Selection Example Source: https://www.nushell.sh/book/line_editor.html Demonstrates how to use quick selection within the history menu by typing '!' to directly select an entry without scrolling. This example shows selecting the fourth entry (index 3). ```nushell !3 ``` -------------------------------- ### Launch Nu Source: https://www.nushell.sh/book/installation.html After installation, launch the Nushell interactive shell by typing 'nu'. ```shell $ nu /home/sophiajt/Source> ``` -------------------------------- ### Date and Time Formatting Source: https://www.nushell.sh/book/types_of_data.html Demonstrates how to get the current date and time and format it as a Unix epoch timestamp. Requires the `date` command. ```nushell date now # => Mon, 12 Aug 2024 13:59:22 -0400 (now) # Format as Unix epoch date now | format date '%s' # => 1723485562 ``` -------------------------------- ### String Interpolation Example Source: https://www.nushell.sh/book/types_of_data.html Illustrates how to create strings using variables with string interpolation. Multiple quote styles are supported. ```nushell let audience: string = "World" $"Hello, ($audience)" # => Hello, World ``` -------------------------------- ### Python eval() example Source: https://www.nushell.sh/book/how_nushell_code_gets_run.html Demonstrates how Python's eval() function parses and evaluates strings, adding a 'meta' step to the execution process. ```python print("Hello, World!") eval("print('Hello, Eval!')") ``` -------------------------------- ### Boolean Comparison Example Source: https://www.nushell.sh/book/types_of_data.html Shows how boolean values are generated through comparisons and used in conditional logic. The `$env.HOME | path exists` check demonstrates a common use case. ```nushell let mybool: bool = (2 > 1) $mybool # => true let mybool: bool = ($env.HOME | path exists) $mybool # => true ``` ```nushell let num = -2 if $num < 0 { print "It's negative" } # => It's negative ``` -------------------------------- ### Get User Input: Bash vs Nushell Source: https://www.nushell.sh/book/coming_from_bash.html Illustrates how to prompt the user for input and store it in a variable in Bash and Nushell. ```bash read var ``` ```nu let var = input ``` -------------------------------- ### Use a custom command in a pipeline Source: https://www.nushell.sh/book/custom_commands.html This example shows how to pipe a list of numbers into the custom `double` command and observe the doubled output. ```nushell [1 2 3] | double ``` -------------------------------- ### Send menu event with completion_menu Source: https://www.nushell.sh/book/line_editor.html Example of configuring a 'send' event for the 'menu' type, specifically activating the 'completion_menu'. ```yaml ... event: { send: menu name: completion_menu } ... ``` -------------------------------- ### Check Binary Data Signature Source: https://www.nushell.sh/book/types_of_data.html Verifies the initial bytes of a binary file against a known signature. This example checks if a JPEG file starts with `0xffd8`. ```nushell open nushell_logo.jpg | into binary | first 2 | $in == 0x[ff d8] ``` -------------------------------- ### Compare Startup Time with and without Standard Library Source: https://www.nushell.sh/book/standard_library.html Demonstrates the difference in startup time when the standard library is disabled versus when it is enabled. Useful for performance analysis. ```bash nu --no-std-lib -n -c "$nu.startup-time" # => 1ms 125µs 10ns ``` ```bash nu -n -c "$nu.startup-time" # => 4ms 889µs 576ns ``` -------------------------------- ### Fastest REPL Startup Source: https://www.nushell.sh/book/configuration.html Enters the Nushell REPL with minimal startup overhead by disabling the standard library and configuration file loading. This is the fastest way to start the REPL. ```bash nu -n --no-std-lib ``` -------------------------------- ### Install Nushell using Cargo Source: https://www.nushell.sh/book/installation.html Installs the latest Nushell release from crates.io using Cargo. Ensure you have Rust and Cargo installed. Default plugins may need separate installation. ```bash cargo install nu --locked ``` -------------------------------- ### Integer Division Example Source: https://www.nushell.sh/book/types_of_data.html Demonstrates basic integer arithmetic and type checking. The result of integer division is an integer. ```nushell 10 / 2 # => 5 5 | describe # => int ``` -------------------------------- ### Create directories Source: https://www.nushell.sh/book/coming_from_cmd.html Make new directories. ```nushell mkdir ``` -------------------------------- ### Documenting a Nushell module Source: https://www.nushell.sh/book/modules/creating_modules.html Example of how to add documentation to a Nushell module. Documentation is added as commented lines at the beginning of the module file. ```nushell # This module provides utility functions for common tasks. # It includes commands for incrementing numbers and converting ranges to lists. ``` -------------------------------- ### Apply and Preview Table Border Modes Source: https://www.nushell.sh/book/coloring_and_theming.html Demonstrates setting the table border mode to 'rounded' and then to 'psql', showing the first 5 available modes for each setting. ```nu $env.config.table.mode = 'rounded' table --list | first 5 ``` ```nu $env.config.table.mode = 'psql' table --list | first 5 ``` -------------------------------- ### Get specific column values with `get` Source: https://www.nushell.sh/book/working_with_tables.html Use `get` to extract values from a specific column as a list. This is useful when you only need the data within the cells, not the entire column structure. ```nushell ls | get name ``` -------------------------------- ### Define and Call a Function in a Nushell Script Source: https://www.nushell.sh/book/scripts.html Example of a Nushell script defining a function `greet` and then calling it. Definitions can appear anywhere in the script. ```nushell # myscript.nu def greet [name] { ["hello" $name] } greet "world" ``` -------------------------------- ### View Configuration Documentation Source: https://www.nushell.sh/book/configuration.html Displays detailed documentation for Nushell configuration options, piped to `less` for easier viewing. Requires `nu-highlight` for colored output. ```nu config nu --doc | nu-highlight | less -R ``` -------------------------------- ### Apply nullify command to ls output Source: https://www.nushell.sh/book/custom_commands.html This example pipes the output of the `ls` command into the `nullify` command to set the 'name' and 'size' columns to null. ```nushell ls | nullify name size ``` -------------------------------- ### Demonstrate Recursion Error Source: https://www.nushell.sh/book/aliases.html This example shows a common mistake that leads to a recursion error when attempting to redefine a command without backing it up first. ```nushell def ls [] { ls }; ls # Do *NOT* do this! This will throw a recursion error ``` -------------------------------- ### Custom Command with Rest Parameters Source: https://www.nushell.sh/book/cheat_sheet.html Defines a custom command `greet` that accepts any number of string arguments using rest parameters. It then prints each argument. ```nushell def greet [...name: string] { print "hello all:" for $n in $name { print $n } } greet earth mars jupiter venus ``` -------------------------------- ### Creating a Directory with Dynamic Name (Pipeline) Source: https://www.nushell.sh/book/pipelines.html Demonstrates an alternative, more verbose but potentially more readable, method of creating a directory with a dynamic name using a step-by-step pipeline. Each step's output is piped to the next. ```nushell date now # 1: today | $in + 1day # 2: tomorrow | format date '%F' # 3: Format as YYYY-MM-DD | $'($in) Report' # 4: Format the directory name | mkdir $in # 5: Create the directory ``` -------------------------------- ### Install Build Dependencies for RHEL-based Distros Source: https://www.nushell.sh/book/installation.html Install necessary packages for building Nushell on RHEL, Fedora, or Rocky Linux systems. ```shell yum install libxcb openssl-devel libX11-devel ``` -------------------------------- ### Identify Inefficient Standard Library Usage in Startup Files Source: https://www.nushell.sh/book/standard_library.html This command helps identify files in your startup configuration that might be using inefficient syntax for importing standard library modules. Review and update these files to recommended syntax. ```nushell view files | enumerate | flatten | where filename !~ '^std' | where filename !~ '^entry' | where {|file| (view span $file.start $file.end) =~ 'use\W+std[^\/]' } ``` -------------------------------- ### Install Build Dependencies for macOS using Homebrew Source: https://www.nushell.sh/book/installation.html Install required dependencies 'openssl' and 'cmake' using Homebrew on macOS for building Nushell. ```shell brew install openssl cmake ``` -------------------------------- ### Creating a Directory with Dynamic Name (Subexpression) Source: https://www.nushell.sh/book/pipelines.html An example of creating a directory using a subexpression to dynamically generate part of the directory name based on the current date. ```nushell mkdir $'((date now) + 1day | format date '%F') Report' ``` -------------------------------- ### Add Nushell APK Repository and Install Source: https://www.nushell.sh/book/installation.html Configure the APK package manager for Alpine Linux to include the Nushell repository and install Nushell. ```shell echo "https://alpine.fury.io/nushell/" | tee -a /etc/apk/repositories apc update apk add --allow-untrusted nushell ``` -------------------------------- ### Call 'greet' command with two arguments Source: https://www.nushell.sh/book/custom_commands.html This demonstrates calling the 'greet' command with two required positional arguments, 'Wei' and 'Mei', resulting in a formatted greeting. ```nushell greet Wei Mei ``` -------------------------------- ### Import a module and its definitions Source: https://www.nushell.sh/book/modules/using_modules.html Use the `use` command to import functionality from a module. The standard library is readily available. ```nushell use ``` ```nushell use std/log log info "Hello, Modules" ``` -------------------------------- ### Get Secret Input: Bash vs Nushell Source: https://www.nushell.sh/book/coming_from_bash.html Shows how to securely get secret input from the user without echoing keystrokes in Bash and Nushell. ```bash read -s secret ``` ```nu let secret = input -s ``` -------------------------------- ### Multi-line Command Formatting Examples Source: https://www.nushell.sh/book/style_guide.html Demonstrates correct usage of multi-line formatting for pipelines, lists, records, and closures. It's recommended for scripts and complex commands exceeding 80 characters or containing nested structures. ```nushell [[status]; [UP] [UP]] | all {|el| $el.status == UP } [1 2 3 4] | reduce {|elt, acc| $elt + $acc } {x: 1, y: 2} [ {name: "Teresa", age: 24}, {name: "Thomas", age: 26} ] let selectedProfile = (for it in ($credentials | transpose name credentials) { echo $it.name }) ``` ```nushell [[status]; [UP] [UP]] | all { |el| # too few "\n" before "}": one "\n" is required $el.status == UP} # too many spaces before "2": one space is required (like in one-line format) [1 2 3 4] | reduce {|elt, acc| $elt + $acc } { # too many "\n" before "x": one-line format required as no nested lists or record exist x: 1, y: 2 } # too few "\n" before "{": multi-line format required as there are two nested records [{name: "Teresa", age: 24}, {name: "Thomas", age: 26}] let selectedProfile = ( # too many "\n" before "foo": no "\n" is allowed for it in ($credentials | transpose name credentials) { echo $it.name }) ``` -------------------------------- ### NUON Data Structure Example Source: https://www.nushell.sh/book/loading_data.html This example shows a NUON data structure, which is a superset of JSON and allows for comments and optional commas, making it more human-friendly. ```nushell { menus: [ # Configuration for default nushell menus # Note the lack of source parameter { name: completion_menu only_buffer_difference: false marker: "| " type: { layout: columnar columns: 4 col_width: 20 # Optional value. If missing all the screen width is used to calculate column width col_padding: 2 } style: { text: green selected_text: green_reverse description_text: yellow } } ] } ``` -------------------------------- ### Define 'greet' command with multiple parameters (spaces) Source: https://www.nushell.sh/book/custom_commands.html This defines a 'greet' command that accepts two required positional parameters, 'name1' and 'name2', separated by spaces in the parameter list. ```nushell def greet [name1 name2] { $"Hello, ($name1) and ($name2)!" } ``` -------------------------------- ### Configure Completion Options Source: https://www.nushell.sh/book/custom_completions.html Demonstrates how to configure custom completion behavior, such as case sensitivity, sorting, and matching algorithm, by returning a record from the completer command. ```nushell def animals [] { { options: { case_sensitive: false, completion_algorithm: substring, sort: false, }, completions: [cat, rat, bat] } } def my-command [animal: string@animals] { print $animal } ``` -------------------------------- ### Until event with menu and menunext Source: https://www.nushell.sh/book/line_editor.html Configures a keybinding to first try opening a completion menu, and if pressed again while the menu is active, move to the next item. ```nushell $env.config.keybindings ++= [{ name: completion_menu modifier: control keycode: char_t mode: emacs event: { until: [ { send: menu name: completion_menu } { send: menunext } ] } }] ``` -------------------------------- ### Example of Invalid Shell Error Source: https://www.nushell.sh/book/default_shell.html This is an example of an error message you might encounter if Nu is not listed in the '/etc/shells' file when trying to change your login shell using 'chsh'. ```text chsh: /home/username/.cargo/bin/nu is an invalid shell ``` -------------------------------- ### Get List Item Using a Variable Index Source: https://www.nushell.sh/book/working_with_lists.html Use the `get` command to retrieve a list item when the index is stored in a variable. This provides dynamic access to list elements. ```nushell let names = [Mark Tami Amanda Jeremy] let index = 1 $names | get $index # gives Tami ``` -------------------------------- ### Access record keys with spaces using get Source: https://www.nushell.sh/book/navigating_structured_data.html Alternatively, use the `get` command with the quoted key name to access record values, especially useful for keys with spaces. ```nushell let record_example = { "key x":12 "key y":4 } $record_example | get "key x" ``` -------------------------------- ### Viewing module help Source: https://www.nushell.sh/book/modules/creating_modules.html After importing a module with `use`, you can view its exported commands and descriptions using the `help` command. ```nushell use my-utils * help my-utils ``` -------------------------------- ### Import and Use Renamed Submodule Commands Source: https://www.nushell.sh/book/modules/creating_modules.html Imports all definitions from `my-utils` and demonstrates that the `go home` command is now available, while the direct `home` command is not, due to the submodule export structure. ```nushell use my-utils * # => As expected: go home # => works home # => Error: command not found ``` -------------------------------- ### Using `get` to Access a Table Row Source: https://www.nushell.sh/book/navigating_structured_data.html Demonstrates using the `get` command with a row index (1) to retrieve a specific row from the table. This is an alternative to direct cell-path access. ```nushell $data | get 1 ``` -------------------------------- ### Get Specific Value from JSON Source: https://www.nushell.sh/book/loading_data.html After opening a JSON file, use the 'get' command to extract a specific field's value. Requires the file to be parsed into a table first. ```nushell open editors/vscode/package.json | get version ``` -------------------------------- ### View All Commands Source: https://www.nushell.sh/book/quick_tour.html Use `help commands` to view a table of all available commands (excluding externals). This output can be piped to other commands for further processing. ```nushell help commands ``` -------------------------------- ### Example of History Menu Search Result Source: https://www.nushell.sh/book/line_editor.html After filtering and selecting an entry from the history menu, the typed words are replaced by the selected command. This example shows a more complex command that might be selected. ```nushell let a = (ls | where size > 10MiB) ``` -------------------------------- ### Define a simple custom command Source: https://www.nushell.sh/book/custom_commands.html Defines a basic custom command named `greet` that takes one argument and returns a formatted string. This is useful for encapsulating reusable logic. ```nushell def greet [name] { $"Hello, ($name)!" } ``` -------------------------------- ### Example of History Menu Search Input Source: https://www.nushell.sh/book/line_editor.html When the history menu is activated, any text typed will filter the history. This example shows a simple variable assignment that could be part of a command in history. ```nushell let a = () ``` -------------------------------- ### Fetch GitHub Contributors using http get and select (Nushell) Source: https://www.nushell.sh/book/thinking_in_nu.html Nushell's built-in http get command and native JSON handling simplify fetching and selecting data from APIs, eliminating the need for external tools like curl and jq. ```nushell http get https://api.github.com/repos/nushell/nushell/contributors | select login contributions ``` -------------------------------- ### Define 'greet' command with multiple parameters (linebreaks) Source: https://www.nushell.sh/book/custom_commands.html This defines a 'greet' command that accepts two required positional parameters, 'name1' and 'name2', separated by linebreaks in the parameter list. ```nushell def greet [ name1 name2 ] { $"Hello, ($name1) and ($name2)!" } ``` -------------------------------- ### Import Plugin by Name Source: https://www.nushell.sh/book/plugins.html Use this command to immediately load a registered plugin into the current Nushell session. The plugin name is used without the `nu_plugin` prefix. ```bash plugin use cool ``` -------------------------------- ### Get the current date Source: https://www.nushell.sh/book/coming_from_cmd.html Retrieve the current date and time. ```nushell date now ``` -------------------------------- ### Basic Pipeline: Open, Update, Save Source: https://www.nushell.sh/book/pipelines.html Demonstrates a typical pipeline flow: opening a file, updating a specific field, and saving the result to a new file. This is useful for configuration file manipulation. ```nushell open Cargo.toml | update workspace.dependencies.base64 0.24.2 | save Cargo_new.toml ``` -------------------------------- ### Get help for operators Source: https://www.nushell.sh/book/quick_tour.html Accesses the in-shell help documentation for Nushell operators. ```nushell help operators ``` -------------------------------- ### Get help for escapes Source: https://www.nushell.sh/book/quick_tour.html Accesses the in-shell help documentation for Nushell escape sequences. ```nushell help escapes ``` -------------------------------- ### View Configuration Documentation Source: https://www.nushell.sh/book/configuration.html Displays detailed documentation for Nushell configuration options. This command uses `nu-highlight` and can be piped to a pager like `bat` or `less`. ```nu config nu --doc | nu-highlight | bat ``` ```nu config nu --doc | nu-highlight | less -R ``` -------------------------------- ### Get the current time Source: https://www.nushell.sh/book/coming_from_cmd.html Retrieve the current time, formatted to show hours, minutes, and seconds. ```nushell date now | format date "%H:%M:%S" ``` -------------------------------- ### Configure Advanced Color Settings with Hex and Attributes Source: https://www.nushell.sh/book/coloring_and_theming.html This example shows how to configure colors using hex codes and attributes like 'bold' (bli). It also demonstrates setting only the foreground color for specific elements. ```nushell $env.config.color_config.separator = "#88b719" # this sets only the foreground color like PR #486 $env.config.color_config.leading_trailing_space_bg = white # this sets only the foreground color in the original style $env.config.color_config.header = { # this is like PR #489 fg: "#B01455", # note, quotes are required on the values with hex colors bg: "#ffb900", # note, commas are not required, it could also be all on one line attr: bli # note, there are no quotes around this value. it works with or without quotes } $env.config.color_config.datetime = "#75507B" $env.config.color_config.filesize = "#729fcf" $env.config.color_config.row_index = { # note, that this is another way to set only the foreground, no need to specify bg and attr fg: "#e50914" } ``` -------------------------------- ### Capture Span Metadata Source: https://www.nushell.sh/book/creating_errors.html Use the 'metadata' command to get the span of an argument for error reporting. ```nushell let span = (metadata $x).span; ``` -------------------------------- ### Define Custom Completions with Descriptions and Styles Source: https://www.nushell.sh/book/custom_completions.html This example defines a custom completion function that returns records with `value`, `description`, and `style` fields. This allows for richer completion menus with visual cues. ```nushell def my_commits [] { [ { value: "5c2464", description: "Add .gitignore", style: red }, # "attr: ub" => underlined and bolded { value: "f3a377", description: "Initial commit", style: { fg: green, bg: "#66078c", attr: ub } } ] } ``` -------------------------------- ### Create a New Overlay Verbose Source: https://www.nushell.sh/book/overlays.html Uses the `overlay new` command as a shortcut to create a new overlay named 'scratchpad'. Custom definitions are then added to this new overlay. ```nushell (zero)> overlay use spam (spam)> overlay new scratchpad (scratchpad)> def eggs [] { "eggs" } ``` -------------------------------- ### Get help for a command Source: https://www.nushell.sh/book/quick_tour.html Shows how to access the in-shell help system for a specific command like `ls`. ```nushell help ls ``` -------------------------------- ### Define 'greet' command with multiple parameters (commas) Source: https://www.nushell.sh/book/custom_commands.html This defines a 'greet' command that accepts two required positional parameters, 'name1' and 'name2', separated by commas in the parameter list. ```nushell def greet [name1, name2] { $"Hello, ($name1) and ($name2)!" } ``` -------------------------------- ### Get Command Help (Nushell) Source: https://www.nushell.sh/book/coming_from_bash.html Retrieves help information for a specific command or lists/searches available commands. ```nushell help ``` ```nushell help commands ``` ```nushell help --find ``` -------------------------------- ### Nushell Static Parsing Example Source: https://www.nushell.sh/book/thinking_in_nu.html Shows a scenario where dynamically generating source code and then sourcing it fails due to Nushell's static parsing, resulting in a file not found error. ```nushell ("print Hello" | save output.nu; source output.nu) ``` -------------------------------- ### Single-quoted string example Source: https://www.nushell.sh/book/working_with_strings.html Use single-quoted strings for simple text literals. They do not interpret escape characters. ```nushell 'hello world' # => hello world 'The end' # => The # => end ``` -------------------------------- ### Float Division Example Source: https://www.nushell.sh/book/types_of_data.html Shows division with floating-point numbers. Note that decimal values in Nushell are approximate. ```nushell 2.5 / 5.0 # => 0.5 ``` ```nushell 10.2 * 5.1 # => 52.01999999999999 ``` -------------------------------- ### Hello, World! in Nushell Source: https://www.nushell.sh/book/how_nushell_code_gets_run.html A basic Nushell program that prints 'Hello, World!'. Run using `nu hello.nu`. ```nushell # hello.nu print "Hello, World!" ``` -------------------------------- ### Edit event: insertstring Source: https://www.nushell.sh/book/line_editor.html Example of configuring an 'edit' event to insert a string at the current prompt location. ```yaml ... event: { edit: insertstring value: "MY NEW STRING" } ... ``` -------------------------------- ### Using a let variable with source Source: https://www.nushell.sh/book/how_nushell_code_gets_run.html Demonstrates how a 'let' variable can be used with the 'source' command. This is evaluated at runtime. ```nushell let my_path = "~/nushell-files" source $"($my_path)/common.nu" ``` -------------------------------- ### Get List Length Source: https://www.nushell.sh/book/working_with_lists.html Determine the number of items in a list using the `length` command. This is useful for iteration or validation. ```nushell [red green blue] | length ``` -------------------------------- ### Call a greeting command with a named flag Source: https://www.nushell.sh/book/custom_commands.html Demonstrates calling the `greet` command with both a positional parameter and an optional named flag. Shows examples where the flag is provided and where it is omitted. ```nushell greet Lucia --age 23 # => ╭──────┬───────╮ # => │ name │ Lucia │ # => │ age │ 23 │ # => ╰──────┴───────╯ greet --age 39 Ali # => ╭──────┬─────╮ # => │ name │ Ali │ # => │ age │ 39 │ # => ╰──────┴─────╯ greet World # => ╭──────┬───────╮ # => │ name │ World │ # => │ age │ │ ``` -------------------------------- ### Get DataFrame Schema Source: https://www.nushell.sh/book/dataframes.html Retrieves and displays the schema of a DataFrame, including column names and their inferred data types. ```nushell $df_0 | polars schema # => ╭───────────┬─────╮ # => │ anzsic06 │ str │ # => │ Area │ str │ # => │ year │ i64 │ # => │ geo_count │ i64 │ # => │ ec_count │ i64 │ # => ╰───────────┴─────╯ ``` -------------------------------- ### Get the present working directory Source: https://www.nushell.sh/book/coming_from_cmd.html Access the current working directory path stored in the PWD environment variable. ```nushell $env.PWD ``` -------------------------------- ### Call Command with Rest Parameters Source: https://www.nushell.sh/book/custom_commands.html Demonstrates calling the 'multi-greet' command with multiple string arguments, which are processed individually. ```nushell multi-greet Elin Lars Erik # => Hello, Elin! # => Hello, Lars! # => Hello, Erik! ``` -------------------------------- ### Edit event: moverightuntil Source: https://www.nushell.sh/book/line_editor.html Example of configuring an 'edit' event to move the cursor right until a specific character is found. ```yaml ... event: { edit: moverightuntil value: "S" } ... ``` -------------------------------- ### Parameterize Nushell Script with `main` Source: https://www.nushell.sh/book/scripts.html Demonstrates using a `main` command in a Nushell script to accept positional parameters. Arguments are passed after the script name. ```nushell # myscript.nu def main [x: int] { $x + 10 } ``` ```bash nu myscript.nu 100 # => 110 ``` -------------------------------- ### Custom Command with Switch Flag and Shorthand Source: https://www.nushell.sh/book/cheat_sheet.html Defines a custom command `greet` with a required string `name`, an optional integer flag `--age` (shorthand `-a`), and a boolean switch flag `--twice`. The output depends on whether `--twice` is used. ```nushell def greet [ name: string --age (-a): int --twice ] { if $twice { [$name $age $name $age] } else { [$name $age] } } greet -a 10 --twice hello ``` -------------------------------- ### Nushell variable name restrictions Source: https://www.nushell.sh/book/variables Illustrates that variable names starting with '$' are allowed in Nushell and are equivalent to names without the '$'. ```nushell let $var = 42 # identical to `let var = 42` ``` -------------------------------- ### Sequential REPL Commands Source: https://www.nushell.sh/book/how_nushell_code_gets_run.html Shows how commands executed in separate REPL entries work due to environment merging between cycles. ```nushell > cd spam > source-env foo.nu ``` -------------------------------- ### Interact with Context-Aware Completions Source: https://www.nushell.sh/book/custom_completions.html Demonstrates the interactive usage of the context-aware custom completion defined previously. Shows how tab completion provides relevant suggestions based on previous input. ```nushell >| my-command cat dog eel ``` ```nushell >| my-command dog Lulu Enzo ``` ```nushell >my-command dog enzo The dog is named Enzo ``` -------------------------------- ### Call a greeting command with a default value Source: https://www.nushell.sh/book/custom_commands.html Demonstrates calling the `greet` command with a default parameter value. The first call uses the default, while the second overrides it. ```nushell greet # => Hello, Nushell! greet world # => Hello, World! ``` -------------------------------- ### Create a Range of Numbers Source: https://www.nushell.sh/book/types_of_data.html Generates a sequence of numbers from a start to an end value. Supports an optional stride for custom increments. ```nushell 1..5 ``` -------------------------------- ### Hello, World! in Rust Source: https://www.nushell.sh/book/how_nushell_code_gets_run.html A simple 'Hello, World!' program in Rust. Requires compilation using `rustc main.rs` and execution of the binary. ```rust // main.rs fn main() { println!("Hello, World!"); } ``` -------------------------------- ### Custom Command with String Parameter Source: https://www.nushell.sh/book/cheat_sheet.html Defines a custom command named `greet` that accepts a single string argument `name`. The command returns a greeting string. ```nushell def greet [name: string] { $"hello ($name)" } ``` -------------------------------- ### Get Unique Values from a Series using `unique` Source: https://www.nushell.sh/book/dataframes.html Use `polars unique` on a Series to retrieve only the unique values present in that column. ```nushell $df_1 | polars get first | polars unique ``` -------------------------------- ### Get original index with enumerate and select Source: https://www.nushell.sh/book/navigating_structured_data.html To retain the original row index when using `select`, pipe the data through `enumerate` first. ```nushell $data | enumerate | select 1 ``` -------------------------------- ### Demonstrate Overlay Precedence Source: https://www.nushell.sh/book/overlays.html Shows how defining a function in one overlay and then using another overlay that redefines it results in the latter's definition being used. Re-using an overlay brings it to the top of the stack. ```nushell (zero)> def foo [] { "foo-in-zero" } (zero)> overlay use spam (spam)> foo foo (spam)> overlay use zero (zero)> foo foo-in-zero (zero)> overlay list ───┬────── 0 │ spam 1 │ zero ───┴────── ```