Table of Contents

1.0 Overview

1.1 Console/NSH Front End

1.2 Command Overview

1.3 Conditional Command Execution

1.4 Looping

1.5 Built-In Variables

1.6 Current Working Directory

1.7 Environment Variables

1.8 NSH Start-Up Script
2.0 Commands.

2.1 Evaluate Expression (test)

2.2 Add a Routing Table Entry (addroute)

2.3 Access the ARP table (arp)

2.4 Base64 Decode (base64dec)

2.5 Base64 Encode (base64enc)

2.6 Extract Base File/Directory Name (basename)

2.7 Terminate a Loop (break)

2.8 Concatenate Files (cat)

2.9 Change Current Working Directory (cd)

2.10 Compare Files (cmp)

2.11 Copy Files (cp)

2.12 Show or set the date and time (date)

2.13 Copy and Convert Files (dd)

2.14 Delete a Routing Table Entry (delroute)

2.15 Show volume status (df)

2.16 Extract Path to a File/Directory (dirname)

2.17 Dump Buffered SYSLOG Output (dmesg)

2.18 Echo Strings and Variables (echo)

2.19 Show Environment Variables (env)

2.20 Execute User Code (exec)

2.21 Exit NSH (exit)

2.22 Set an Environment Variable (export)

2.23 Show Memory Manager Status (free)

2.24 Get File Via TFTP (get)

2.25 Show Usage Command Usage (help)

2.26 Hexadecimal Dump of File or Device (hexdump)

2.27 Manage Network Configuration (ifconfig)

2.28 Take a network down (ifdown)

2.29 Bring a network up (ifup)

2.30 Install an OS module (insmod)

2.31 Show Interrupt Status (irqinfo)

2.32 Send a signal to a task (kill)

2.33 Setup/teardown the Loop Device (losetup)

2.34 List to a File or Directory (ln)

2.35 List Directory Contents (ls)

2.36 Show information about installed OS modules (lsmod)

2.37 Calculate MD5 (md5)

2.38 Access Memory (mb, mh, and mw)

2.39 Show Current Tasks and Threads (ps)

2.40 Create a Directory (mkdir)

2.41 Create a FAT File System (mkfatfs)

2.42 Create a FIFO (mkfifo)

2.43 Create a RAMDISK (mkrd)

2.44 Mount a File System (mount)

2.45 Rename a File (mv)

2.46 Mount an NFS File System (nfsmount)

2.47 Lookup a network address (nslookup)

2.48 Change a User's Password (passwd)

2.49 Manage Power Management Subsystem (pmconfig)

2.50 Shut the system down (poweroff)

2.51 Send File Via TFTP (put)

2.52 Show Current Working Directory (pwd)

2.53 Show target of a link (readlink)

2.54 Reset and reboot the system (reboot)

2.55 Remove a File (rm)

2.56 Remove a Directory (rmdir)

2.57 Remove on OS Module (rmmod)

2.58 Show routing table (route)

2.59 Start/Stop the OpenAMP RPC Tunnel (rptun)

2.60 Set a Variable (set)

2.61 Execute an NSH Script (sh)

2.62 Shut the system down (shutdown)

2.63 Wait for Seconds (sleep)

2.64 Start the Telnet Daemon (telnetd)

2.65 Time execution of another command (time)

2.66 Set the Size of a File (truncate)

2.67 Unmount a File System (umount)

2.68 Print system information (uname)

2.69 Unset an Environment Variable (unset)

2.70 URL Decode (urldecode)

2.71 URL Encode (urlencode)

2.72 Add a New User (useradd)

2.73 Delete a user (userdel)

2.74 Wait for Microseconds (usleep)

2.75 Get File Via HTTP (wget)

2.76 Hexadecimal Dump of Memory (xd)
3.0 Built-In Commands

3.1 Check Network Peer (ping/pin6)
4.0 Configuration Settings

4.1 Command Dependencies on Configuration Settings

4.2 Built-In Command Dependencies on Configuration Settings

4.3 NSH-Specific Configuration Settings
5.0 Customizing the NuttShell

5.1 The NSH Library and NSH Initialization

5.2 NSH Commands

5.3 NSH "Built-In" Applications

5.4 Customizing NSH Initialization
6.0 Shell Login

6.1 Enabling Shell Logins

6.2 Verification of Credentials

6.3 Password Files

6.4 Creating a Password File for a ROMFS File System
Index


NuttShell (NSH)

Last Updated: November 3, 2019



1.0 Overview

The NSH Library. The apps/nshlib sub-directory contains the NuttShell (NSH) library. This library can easily to linked to produce a NSH application (See as an example apps/examples/nsh). The NSH Library provides a simple shell application for NuttX.

1.1 Console/NSH Front End

NSH Consoles. Using settings in the configuration file, NSH may be configured to use (1) the serial stdin/out, (2) a USB serial device (such as CDC/ACM), or (3) a telnet connection as the console. Or, perhaps even all at once since or BOTH. An indefinite number of telnet sessions are supported.

Start-Up prompt. When NSH is started, you will see the a welcome message such the following on the selected console:

The greeting may also include NuttX versioning information if you are using a versioned copy of NuttX. nsh> is the NSH prompt and indicates that you may enter a command from the console.

USB console startup. When using a USB console, the start-up sequence differs a little: In this case, you are required to press ENTER three times. Then NSH prompt will appear as described above. This is required for the following reasons:

  1. This assures that the USB connection is stable. The USB connection may be made, broken, and re-established a few times if the USB cable is not yet fully seated. Waiting for ENTER to be pressed three times assures that the connection is stable.
  2. The establishment of the connection is two step process: First, the USB serial connection is made with the host PC. Then the application that uses the serial interface is started on the host. When the serial connection is established on the host, the host operating system may send several AT modem commands to the host depending upon how the host serial port is configured. By waiting for ENTER to be pressed three consecutive times, all of these modem commands will go to the bit-bucket and will not be interpreted as NSH command input.
  3. Similarly, in the second step when the applications is started, there may be additional AT modem commands sent out the serial port. Most serial terminal programs will do this unless they are specifically configured to suppress the modem command output. Waiting for the ENTER input eliminates the invalid command errors from both (2) and (3).
  4. Finally, if NSH did not wait for some positive indication that the serial terminal program is up and running, then the output of the NSH greeting and initial NSH prompt would be lost.

Extended Command Line Editing. By default, NuttX uses a simple command line editor that allows command entry after the nsh> and supports only the backspace key for editing. However, a more complete command line editor can be selected by setting CONFIG_NSH_CLE=y in the NuttX configuration file. When that option is selected, the following EMACS-like line editing commands are supported:

Key Binding Editor Action
^A Move cursor to start of the line
^B Move left one character
^D or Del Delete a single character at the cursor position
^E Move cursor to end of current line
^F Move right one character
^H or Backspace Delete character, left (backspace)
^K Delete to the end of the line
^U Delete the entire line

1.2 Command Overview

Simple, Re-directed, and Background Commands. The NuttShell (NSH) is a simple shell application. NSH supports the following commands forms:

Where:

nice'd Background Commands NSH executes at the mid-priority (128). Backgrounded commands can be made to execute at higher or lower priorities using nice:

Where <niceness> is any value between -20 and 19 where lower (more negative values) correspond to higher priorities. The default niceness is 10.

Multiple commands per line. NSH will accept multiple commands per command line with each command separated with the semi-colon character (;).

Optional Syntax Extensions Because these features commit significant resources, they are disabled by default.

1.3 Conditional Command Execution

An if-then[-else]-fi construct is also supported in order to support conditional execution of commands. This works from the command line but is primarily intended for use within NSH scripts (see the sh command). The syntax is as follows:

Where <cmd> is a simple command. The command success value of zero is treated true; a non-zero command failure value is treated false. The test command is frequently used for comparisons.

1.4 Looping

Looping Constructs. while-do-done and until-do-done looping constructs are also supported. These work from the command line but are primarily intended for use within NSH scripts (see the sh command).

Where <cmd> is a simple command. The command success value of zero is treated true; a non-zero command failure value is treated false. The test command is frequently used for comparisons.

The break Command. A break command is also supported. The break command is only meaningful within the body of the a while or until loop, between the do and done tokens. If the break command is executed within the body of a loop, the loop will immediately terminate and execution will continue with the next command immediately following the done token.

1.5 Built-In Variables

1.6 Current Working Directory

cd and pwd. All path arguments to commands may be either an absolute path or a path relative to the current working directory. The current working directory is set using the cd command and can be queried either by using the pwd command or by using the echo $PWD command.

1.7 Environment Variables

Environment Variables:

1.8 NSH Start-Up Script

NSH Start-Up Script. NSH supports options to provide a start up script for NSH. In general this capability is enabled with CONFIG_NSH_ROMFSETC, but has several other related configuration options as described with the NSH-specific configuration settings. This capability also depends on:

Default Start-Up Behavior. The implementation that is provided is intended to provide great flexibility for the use of Start-Up files. This paragraph will discuss the general behavior when all of the configuration options are set to the default values.

In this default case, enabling CONFIG_NSH_ROMFSETC will cause NSH to behave as follows at NSH startup time:

Modifying the ROMFS Image. The contents of the /etc directory are retained in the file apps/nshlib/nsh_romfsimg.h OR, if CONFIG_NSH_ARCHROMFS is defined, include/arch/board/rcs.template). In order to modify the start-up behavior, there are three things to study:

  1. Configuration Options. The additional CONFIG_NSH_ROMFSETC configuration options discussed with the other NSH-specific configuration settings.
  2. tools/mkromfsimg.sh Script. The script tools/mkromfsimg.sh creates nsh_romfsimg.h. It is not automatically executed. If you want to change the configuration settings associated with creating and mounting the /tmp directory, then it will be necessary to re-generate this header file using the tools/mkromfsimg.sh script.

    The behavior of this script depends upon three things:

    • The configuration settings then installed configuration.
    • The genromfs tool (available from http://romfs.sourceforge.net).
    • The file apps/nshlib/rcS.template (OR, if CONFIG_NSH_ARCHROMFS is defined include/arch/board/rcs.template.

  3. rcS.template. The file apps/nshlib/rcS.template contains the general form of the rcS file; configured values are plugged into this template file to produce the final rcS file.

NOTE: apps/nshlib/rcS.template generates the standard, default nsh_romfsimg.h file. If CONFIG_NSH_ARCHROMFS is defined in the NuttX configuration file, then a custom, board-specific nsh_romfsimg.h file residing in the boards/<arch>/<chip>/<board>/include directory will be used. NOTE when the OS is configured, include/arch/board will be linked to boards/<arch>/<chip>/<board>/include.

All of the startup-behavior is contained in rcS.template. The role of mkromfsimg.sh is to (1) apply the specific configuration settings to rcS.template to create the final rcS, and (2) to generate the header file nsh_romfsimg.h containing the ROMFS file system image.

Further Information. See the section on Customizing the NuttShell for additional, more detailed information about the NSH start-up script and how to modify it.

2.0 Commands

2.1 Evaluate Expression (test)

Command Syntax:

Synopsis. These are two alternative forms of the same command. They support evaluation of a boolean expression which sets $?. This command is used most frequently as the conditional command following the if in the if-then[-else]-fi construct.

Expression Syntax:

2.2 Add a Routing Table Entry (addroute)

Command Syntax:

Synopsis. This command adds an entry in the routing table. The new entry will map the IP address of a router on a local network (<router>) to an external network characterized by the <target> IP address and a network mask <netmask>

The netmask may also be expressed using IPv4 CIDR or IPv6 slash notation. In that case, the netmask need not be provided.

Example:

which is equivalent to

The second form of the addroute command can be used to set the default gateway.

2.3 Access the ARP table (arp)

Command Syntax:

Synopsis. Access the OS ARP table.

Example:

2.4 Base64 Decode (base64dec)

Command Syntax:

Synopsis. To be provided.

2.5 Base64 Encode (base64enc)

Command Syntax:

Synopsis. To be provided.

2.6 Extract Base File/Directory Name (basename)

Command Syntax:

Synopsis. Extract the final string from a <path> by removing the preceding path segments and (optionally) removing any trailing <suffix>.

2.7 Terminate a Loop (break)

Command Syntax:

Synopsis. The break command is only meaningful within the body of the a while or until loop, between the do and done tokens. Outside of a loop, break command does nothing. If the break command is executed within the body of a loop, the loop will immediately terminate and execution will continue with the next command immediately following the done token.

2.8 Concatenate Files (cat)

Command Syntax:

Synopsis. This command copies and concatenates all of the files at <path> to the console (or to another file if the output is redirected).

2.9 Change Current Working Directory (cd)

Command Syntax:

Synopsis. Changes the current working directory (PWD). Also sets the previous working directory environment variable (OLDPWD).

Forms:

2.10 Compare Files (cmp)

Command Syntax:

Synopsis. Compare of the contents of the file at <path1> with the contents of the file at <path2>. Returns an indication only if the files differ.

2.11 Copy Files (cp)

Command Syntax:

Synopsis. Copy of the contents of the file at <source-path> to the location in the file system indicated by <dest-path>.

2.12 Show or set the date and time (date)

Command Syntax:

Synopsis. Show or set the current date and time.

Only one format is used both on display and when setting the date/time: MMM DD HH:MM:SS YYYY. For example,

24-hour time is used.

2.13 Copy and Convert Files (dd)

Command Syntax:

Synopsis. Copy blocks from <infile> to <outfile>. <infile> or <outfile> may be the path to a standard file, a character device, or a block device. Examples follow:

  1. Read from character device, write to regular file. This will create a new file of the specified size filled with zero.
      nsh> ls -l /dev
      /dev:
       crw-rw-rw-       0 zero
      nsh> dd if=/dev/zero of=/tmp/zeros bs=64 count=16
      nsh> ls -l /tmp
      /tmp:
       -rw-rw-rw-    1024 ZEROS
      
  2. Read from character device, write to block device. This will fill the entire block device with zeros.
    • nsh> ls -l /dev
      /dev:
       brw-rw-rw-       0 ram0
       crw-rw-rw-       0 zero
      nsh> dd if=/dev/zero of=/dev/ram0
      
  3. Read from a block device, write to a character device. This will read the entire block device and dump the contents in the bit bucket.
    • nsh> ls -l /dev
      /dev:
       crw-rw-rw-       0 null
       brw-rw-rw-       0 ram0
      nsh> dd if=/dev/ram0 of=/dev/null
      

2.14 Delete a Routing Table Entry (delroute)

Command Syntax:

Synopsis. The entry removed will be the first entry in the routing table that matches the external network characterized by the <target> IP address and the network mask <netmask>

The netmask may also be expressed using IPv4 CIDR or IPv6 slash notation. In that case, the netmask need not be provided.

Example:

which is equivalent to

2.15 Show Volume Status (df)

Command Syntax:

Synopsis. Show the state of each mounted volume. As an example:

If CONFIG_NSH_CMDOPT_DF_H is defined in the NuttX configuration, then the df will also support an option -h which may be used to show the volume information in human readable format.

2.16 Extract Path to a File/Directory (dirname)

Command Syntax:

Synopsis. Extract the path string leading up to the full <path> by removing the final directory or file name.

2.17 Dump Buffered SYSLOG Output (dmesg)

Command Syntax:

Synopsis. This command can be used to dump (and clear) the content of any buffered syslog output messages. This command is only available if CONFIG_RAMLOG_SYSLOG is enabled. In that case, syslog output will be collected in an in-memory, circular buffer. Entering the dmesg command will dump the content of that in-memory, circular buffer to the NSH console output. dmesg has the side effect of clearing the buffered data so that entering dmesg again will show only newly buffered data.

2.18 Echo Strings and Variables (echo)

Command Syntax:

Synopsis. Copy the sequence of strings and expanded environment variables to console output (or to a file if the output is re-directed).

The -n option suppresses the trailing newline character.

2.19 Show Environment Variables (env)

Command Syntax:

Synopsis. Show the current name-value pairs in the environment. Example:.

NOTE: NSH local variables are not shown by the env command.

2.20 Execute User Code (exec)

Command Syntax:

Synopsis. Execute the user logic at address <hex-address>. NSH will pause until the execution unless the user logic is executed in background via exec <hex-address> &.

2.21 Exit NSH (exit)

Command Syntax:

Synopsis. Exit NSH. Only useful for the serial front end if you have started some other tasks (perhaps using the exec command) and you would like to have NSH out of the way. For the telnet front-end, exit terminates the telnet session.

2.22 Set an Environment Variable (export)

Command Syntax:

Synopsis. The export command sets an environment variable, or promotes an NSH variable to an environment variable. As examples:

  1. Using export to promote an NSH variable to an environment variable.

      nsh> env
      PATH=/bin
      
      nsh> set foo bar
      nsh> env
      PATH=/bin
      
      nsh> export foo
      nsh> env
      PATH=/bin
      foo=bar
      

    A group-wide environment variable is created with the same value as the local NSH variable; the local NSH variable is removed.

    NOTE: This behavior differs from the Bash shell. Bash would retain the local Bash variable which will shadow the environment variable of the same name and same value.
  2. Using export to set an environment variable

      nsh> export dog poop
      nsh> env
      PATH=/bin
      foo=bar
      dog=poop
      

The export command is not supported by NSH unless both CONFIG_NSH_VARS=y and CONFIG_DISABLE_ENVIRONis not set.

2.23 Show Memory Manager Status (free)

Command Syntax:

Synopsis. Show the current state of the memory allocator. For example,

Where:

2.24 Get File Via TFTP (get)

Command Syntax:

Synopsis. Copy the file at <remote-address> from the host whose IP address is identified by <ip-address>.

Other options:

2.25 Show Usage Command Usage (help)

Command Syntax:

Synopsis. Presents summary information about NSH commands to console.

Options:

2.26 Hexadecimal Dump of File or Device (hexdump)

Command Syntax:

Synopsis. Dump data in hexadecimal format from a file or character device.

The skip and count options are only available if CONFIG_NSH_CMDOPT_HEXDUMP is defined in the NuttX configuration.

2.27 Manage Network Configuration (ifconfig)

Command Syntax:

Synopsis. Multiple forms of the ifconfig command are supported:

  1. With one or no arguments, ifconfig will shows the current configuration of the network and, perhaps, the status of Ethernet device:

      ifconfig
      ifconfig [nic_name]
      

    As an example:

      nsh> ifconfig
      eth0    HWaddr 00:18:11:80:10:06
              IPaddr:10.0.0.2 DRaddr:10.0.0.1 Mask:255.255.255.0
      

    If network statistics are enabled (CONFIG_NET_STATISTICS), then this command will also show the detailed state of network.

  2. If both the network interface name and an IP address are supplied as arguments, then ifconfig will set the address of the Ethernet device:

      ifconfig nic_name ip_address
      
  3. Other forms to be provided

NOTE: This commands depends upon having the procfs file system configured into the system. The procfs file system must also have been mounted with a command like:

2.28 Take a network down (ifdown)

Command Syntax:

Synopsis. Take down the interface identified by the name <interface>.

Example:

2.29 Bring a network up (ifup)

Command Syntax:

Synopsis. Bring up down the interface identified by the name <interface>.

Example:

2.30 Install an OS module (insmod)

Command Syntax:

Synopsis. Install the loadable OS module at <file-path> as module <module-name>.

Example:

2.31 Show Interrupt Status (irqinfo)

Command Syntax:

Synopsis. Show the current count of interrupts taken on all attached interrupts.

Example:.

2.32 Send a signal to a task (kill)

Command Syntax:

Synopsis. Send the <signal> to the task identified by <pid>.

Example:

NOTE: NuttX does not support a FULL POSIX signaling system. A few standard signal names like SIGCHLD, SIGUSR1, SIGUSR2, SIGALRM, and SIGPOLL exist in the system. However, they do not have the default actions that you might expect. Rather, NuttX supports only what are referred to as POSIX real-time signals. These signals may be used to communicate with running tasks, may be use to waiting waiting tasks, etc.

If the configuration option CONFIG_SIG_DEFAULT is enabled, then default actions for the SIGINT and SIGKILL signals (only) will be supported. In that case, as an example, kill -9 (SIGKILL) will, indeed, terminate a task. Caution should be exercised, however, because this is likely to cause memory leaks and to strand resource since there is insufficient clean-up in certain build configurations.

2.33 Setup/teardown the Loop Device (losetup)

Command Syntax 1:

Synopsis. Setup the loop device at <dev-path> to access the file at <file-path> as a block device. In the following example a 256K file is created (dd) and losetup is used to make the file accessible as a block device. A FAT file system is created (mkfatfs) and mounted (mount). Files can then be managed on the loop-mounted file.

Command Syntax 2:

Synopsis. Teardown the setup for the loop device at <dev-path>.

2.34 Link to a File or Directory (ln)

Command Syntax:

Synopsis. The ln command will create a new symbolic link at <link> for the existing file or directory, <target>. This implementation is simplified for use with NuttX in these ways:

2.35 List Directory Contents (ls)

Command Syntax:

Synopsis. Show the contents of the directory at <dir-path>. NOTE: <dir-path> must refer to a directory and no other file system object.

Options:

2.36 Show information about installed OS modules (lsmod)

Command Syntax:

Synopsis. Show information about the currently installed OS modules. This information includes:

Example:

2.37 Calculate MD5 (md5)

Command Syntax:

Synopsis. To be provided.

2.38 Access Memory (mb, mh, and mw)

Command Syntax:

Synopsis. Access memory using byte size access (mb), 16-bit accesses (mh), or 32-bit access (mw). In each case,

Example:

2.39 Show Current Tasks and Threads (ps)

Command Syntax:

Synopsis. Show the currently active threads and tasks. For example,

NOTE: This commands depends upon having the procfs file system configured into the system. The procfs file system must also have been mounted with a command like:

2.40 Create a Directory (mkdir)

Command Syntax:

Synopsis. Create the directory at <path>. All components of <path> except the final directory name must exist on a mounted file system; the final directory must not.

Limited to Mounted File Systems. Recall that NuttX uses a pseudo file system for its root file system. The mkdir command can only be used to create directories in volumes set up with the mount command; it cannot be used to create directories in the pseudo file system.

Example:

2.41 Create a FAT File System (mkfatfs)

Command Syntax:

Synopsis. Format a fat file system on the block device specified by <block-driver> path. The FAT size may be provided as an option. Without the <fatsize> option, mkfatfs will select either the FAT12 or FAT16 format. For historical reasons, if you want the FAT32 format, it must be explicitly specified on the command line.

The -r option may be specified to select the the number of entries in the root directory for FAT12 and FAT16 file systems. Typical values for small volumes would be 112 or 224; 512 should be used for large volumes, such as hard disks or very large SD cards. The default is 512 entries in all cases.

The reported number of root directory entries used with FAT32 is zero because the FAT32 root directory is a cluster chain.

NSH provides this command to access the mkfatfs() NuttX API. This block device must reside in the NuttX pseudo file system and must have been created by some call to register_blockdriver() (see include/nuttx/fs/fs.h).

2.42 Create a FIFO (mkfifo)

Command Syntax:

Synopsis. Creates a FIFO character device anywhere in the pseudo file system, creating whatever pseudo directories that may be needed to complete the <path>. By convention, however, device drivers are place in the standard /dev directory. After it is created, the FIFO device may be used as any other device driver. NSH provides this command to access the mkfifo() NuttX API.

Example

2.43 Create a RAMDISK (mkrd)

Command Syntax:

Synopsis. Create a ramdisk consisting of <nsectors>, each of size <sector-size> (or 512 bytes if <sector-size> is not specified. The ramdisk will be registered as /dev/ram<minor>. If <minor> is not specified, mkrd will attempt to register the ramdisk as /dev/ram0.

Example

Once the ramdisk has been created, it may be formatted using the mkfatfs command and mounted using the mount command.

Example

2.44 Mount a File System (mount)

Command Syntax:

Synopsis. The mount command performs one of two different operations. If no parameters are provided on the command line after the mount command, then the mount command will enumerate all of the current mountpoints on the console.

If the mount parameters are provided on the command after the mount command, then the mount command will mount a file system in the NuttX pseudo-file system. mount performs a three way association, binding:

  1. File System. The '-t <fstype>' option identifies the type of file system that has been formatted on the <block-device>. As of this writing, vfat is the only supported value for <fstype>
  2. Block Device. The <block-device> argument is the full or relative path to a block driver inode in the pseudo file system. By convention, this is a name under the /dev sub-directory. This <block-device> must have been previously formatted with the same file system type as specified by <fstype>
  3. Mount Point. The mount point, <dir-path>, is the location in the pseudo file system where the mounted volume will appear. This mount point can only reside in the NuttX pseudo file system. By convention, this mount point is a subdirectory under /mnt. The mount command will create whatever pseudo directories that may be needed to complete the full path but the full path must not already exist.

After the volume has been mounted in the NuttX pseudo file system, it may be access in the same way as other objects in the file system.

Examples:

Using mount to mount a file system:

Using mount to enumerate mounts:

2.45 Rename a File (mv)

Command Syntax:

Synopsis. Rename the file object at <old-path> to <new-path>. Both paths must reside in the same mounted file system.

2.46 Mount an NFS file system (nfsmount)

Command Syntax:

Synopsis. Mount the remote NFS server directory<remote-path> at <mount-point> on the target machine. <server-address> is the IP address of the remote server.

2.47 Lookup a network address (nslookup)

Command Syntax:

Synopsis. Lookup and print the IP address associated with <host-name>.

2.48 Change a User's Password (passwd)

Command Syntax:

Synopsis. Set the password for the existing user <username> to <password>.

2.49 Manage Power Management Subsystem (pmconfig)

Command Syntax:

Synopsis. Control power management subsystem.

2.50 Shut the system down (poweroff)

Command Syntax:

Synopsis. Shutdown and power off the system immediately. This command depends on board-specific hardware support to power down the system. The optional,decimal numeric argument may be included to provide power off mode to board-specific power off logic.

NOTE: Supporting both the poweroff and shutdown commands is redundant.

2.51 Send File Via TFTP (put)

Command Syntax:

Synopsis. Copy the file at <local-address> to the host whose IP address is identified by <ip-address>.

Other options:

2.52 Show Current Working Directory (pwd)

Command Syntax:

Synopsis. Show the current working directory.

Same as echo $PWD.

2.53 Show target of a link (readlink)

Command Syntax:

Synopsis. Show the target of the soft link at the path <link>.

2.54 Reboot the system (reboot)

Command Syntax:

Synopsis. Reset and reboot the system immediately. This command depends on hardware support to reset the system. The optional, decimal numeric argument <n> may be included to provide a reboot mode to board-specific reboot logic.

NOTE: Supporting both the reboot and shutdown commands is redundant.

2.55 Remove a File (rm)

Command Syntax:

Synopsis. Remove the specified <file-path> name from the mounted file system. Recall that NuttX uses a pseudo file system for its root file system. The rm command can only be used to remove (unlink) files in volumes set up with the mount command; it cannot be used to remove names in the pseudo file system.

Example:

2.56 Remove a Directory (rmdir)

Command Syntax:

Synopsis. Remove the specified <dir-path> directory from the mounted file system. Recall that NuttX uses a pseudo file system for its root file system. The rmdir command can only be used to remove directories from volumes set up with the mount command; it cannot be used to remove directories from the pseudo file system.

Example:

2.57 Remove on OS Module (rmmod)

Command Syntax:

Synopsis. Remove the loadable OS module with the <module-name>. NOTE: An OS module can only be removed if it is not busy.

Example:

2.58 Show routing table (route)

Command Syntax:

Synopsis. Show the contents of routing table for IPv4 or IPv6.

If only IPv4 or IPv6 is enabled, then the argument is optional but, if provided, must match the enabled internet protocol version.

2.59 Start/Stop the OpenAMP RPC Tunnel (rptun)

Command Syntax:

Synopsis. Start or stop the OpenAMP RPC tunnel device at <dev-path>.

2.60 Set a Variable (set)

Command Syntax:

Synopsis. Set the variable <name> to the string <value> and or set NSH parser control options.

For example, a variable may be set like this:

If CONFIG_NSH_VARS is selected, the effect of this set command is to set the local NSH variable. Otherwise, the group-wide environment variable will be set.

If the local NSH variable has already been promoted to an environment variable via the export, then the set command will set the value of the environment variable rather than the local NSH variable.

NOTE: The Bash shell does not work this way. Bash would set the value of both the local Bash variable and the environment variable of the same name to the same value.

If CONFIG_NSH_VARS=y is selected and no arguments are provided, then the set command will list all of the local NSH variables.

Set the exit on error control and/or print a trace of commands when parsing scripts in NSH. The settings are in effect from the point of execution, until they are changed again, or in the case of the initialization script, the settings are returned to the default settings when it exits. Included child scripts will run with the parents settings and changes made in the child script will effect the parent on return.

Example 1 - no exit on command not found

Example 2 - will exit on command not found

Example 3 - will exit on command not found, and print a trace of the script commands

Example 4 - will exit on command not found, and print a trace of the script commands and set foobar to foovalue.

2.61 Execute an NSH Script (sh)

Command Syntax:

Synopsis. Execute the sequence of NSH commands in the file referred to by <script-path>.

2.62 Shut the system down (shutdown)

Command Syntax:

Synopsis. Shutdown and power off the system or, optionally, reset and reboot the system immediately. This command depends on hardware support to power down or reset the system; one, both, or neither behavior may be supported.

NOTE: The shutdown command duplicates the behavior of the poweroff and eboot commands.

2.63 Wait for Seconds (sleep)

Command Syntax:

Synopsis. Pause execution (sleep) for <sec> seconds.

2.64 Time Start the Telnet Daemon (telnetd)

Command Syntax:

Synopsis. Start the Telnet daemon if it is not already running.

The Telnet daemon may be started either programmatically by calling nsh_telnetstart() or it may be started from the NSH command line using this telnetd command.

Normally this command would be suppressed with CONFIG_NSH_DISABLE_TELNETD because the Telnet daemon is automatically started in nsh_main.c. The exception is when CONFIG_NSH_NETLOCAL is selected. In that case, the network is not enabled at initialization but rather must be enabled from the NSH command line or via other applications.

In that case, when nsh_telnetstart() is called before the the network is initialized, it will fail.

2.65 Time execution of another command (time)

Command Syntax:

Synopsis. Perform command timing. This command will execute the following <command> string and then show how much time was required to execute the command. Time is shown with a resolution of 100 microseconds which may be beyond the resolution of many configurations. Note that the <command> must be enclosed in quotation marks if it contains spaces or other delimiters.

Example:

The additional 10 milliseconds in this example is due to the way that the sleep command works: It always waits one system clock tick longer than requested and this test setup used a 10 millisecond periodic system timer. Sources of error could include various quantization errors, competing CPU usage, and the additional overhead of the time command execution itself which is included in the total.

The reported time is the elapsed time from starting of the command to completion of the command. This elapsed time may not necessarily be just the processing time for the command. It may included interrupt level processing, for example. In a busy system, command processing could be delayed if pre-empted by other, higher priority threads competing for CPU time. So the reported time includes all CPU processing from the start of the command to its finish possibly including unrelated processing time during that interval.

Notice that:

Since the sleep command is executed in background, the sleep command completes almost immediately. As opposed to the following where the time command is run in background with the sleep command:

2.66 Set the Size of a File (truncate)

Command Syntax:

Synopsis. Shrink or extend the size of the regular file at <file-path> to the specified<length>.

A <file-path> argument that does not exist is created. The <length> option is NOT optional.

If a <file-path> is larger than the specified size, the extra data is lost. If a <file-path> is shorter, it is extended and the extended part reads as zero bytes.

2.67 Unmount a File System (umount)

Command Syntax:

Synopsis. Un-mount the file system at mount point <dir-path>. The umount command can only be used to un-mount volumes previously mounted using mount command.

Example:

2.68 Print system information (uname)

Command Syntax:

Synopsis. Print certain system information. With no options, the output is the same as -s.

2.69 Unset an Environment Variable (unset)

Command Syntax:

Synopsis. Remove the value associated with the variable <name>. This will remove the name-value pair from both the NSH local variables and the group-wide environment variables. For example:

2.70 URL Decode (urldecode)

Command Syntax:

Synopsis. To be provided.

2.71 URL Encode (urlencode)

Command Syntax:

Synopsis. To be provided.

2.72 Add a New User (useradd)

Command Syntax:

Synopsis. Add a new user with <username> and <password>.

2.73 Delete a user (userdel)

Command Syntax:

Synopsis. Delete the user with the name <username>.

2.74 Wait for Microseconds (usleep)

Command Syntax:

Synopsis. Pause execution (sleep) of <usec> microseconds.

2.75 Get File Via HTTP (wget)

Command Syntax:

Synopsis. Use HTTP to copy the file at <url> to the current directory.

Options:

2.76 Hexadecimal Dump of Memory (xd)

Command Syntax:

Synopsis. Dump <byte-count> bytes of data from address <hex-address>.

Example:

3.0 Built-In Commands

In addition to the commands that are part of NSH listed in the previous section above, there can be additional, external built-in applications that can be added to NSH. These are separately excecuble programs but will appear much like the commands that are a part of NSH. The primary difference from the user's perspective is that help information about the built-in applications is not available directly from NSH. Rather, you will need to execute the application with the -h option to get help about using the built-in applications.

There are several built-in applications in the apps/ repository. No attempt is made here to enumerate all of them. But a few of the more common, useful built-in applications are listed below.

3.1 Check Network Peer (ping/ping6)

Command Syntax:

Synopsis. Test the network communication with a remote peer. Example,

ping6 differs from ping in that it uses IPv6 addressing.

4.0 Configuration Settings

The availability of the above commands depends upon features that may or may not be enabled in the NuttX configuration file. The following table indicates the dependency of each command on NuttX configuration settings. General configuration settings are discussed in the NuttX Porting Guide. Configuration settings specific to NSH as discussed at the bottom of this document.

Note that in addition to general NuttX configuration settings, each NSH command can be individually disabled via the settings in the rightmost column. All of these settings make the configuration of NSH potentially complex but also allow it to squeeze into very small memory footprints.

4.1 Command Dependencies on Configuration Settings

Table. Command Dependencies on Configuration Settings

Command Depends on Configuration Can Be Disabled with
[ !CONFIG_NSH_DISABLESCRIPT CONFIG_NSH_DISABLE_TEST
addroute CONFIG_NET && CONFIG_NET_ROUTE CONFIG_NSH_DISABLE_ADDROUTE
arp CONFIG_NET && CONFIG_NET_ARP CONFIG_NSH_DISABLE_ARP
base64dec CONFIG_NETUTILS_CODECS && CONFIG_CODECS_BASE64 CONFIG_NSH_DISABLE_BASE64DEC
base64enc CONFIG_NETUTILS_CODECS && CONFIG_CODECS_BASE64 CONFIG_NSH_DISABLE_BASE64ENC
basename   CONFIG_NSH_DISABLE_BASENAME
break !CONFIG_NSH_DISABLESCRIPT && !CONFIG_NSH_DISABLE_LOOPS  
cat   CONFIG_NSH_DISABLE_CAT
cd !CONFIG_DISABLE_ENVIRON CONFIG_NSH_DISABLE_CD
cmp   CONFIG_NSH_DISABLE_CMP
cp   CONFIG_NSH_DISABLE_CP
date
CONFIG_NSH_DISABLE_DATE
dd   CONFIG_NSH_DISABLE_DD
delroute CONFIG_NET && CONFIG_NET_ROUTE CONFIG_NSH_DISABLE_DELROUTE
df !CONFIG_DISABLE_MOUNTPOINT && CONFIG_FS_READABLE3 CONFIG_NSH_DISABLE_DF
dirname   CONFIG_NSH_DISABLE_DIRNAME
dmesg CONFIG_RAMLOG_SYSLOG CONFIG_NSH_DISABLE_DMESG
echo
CONFIG_NSH_DISABLE_ECHO
env CONFIG_FS_PROCFS && !CONFIG_DISABLE_ENVIRON && !CONFIG_PROCFS_EXCLUDE_ENVIRON CONFIG_NSH_DISABLE_ENV
exec
CONFIG_NSH_DISABLE_EXEC
exit
CONFIG_NSH_DISABLE_EXIT
export CONFIG_NSH_VARS && !CONFIG_DISABLE_ENVIRON CONFIG_NSH_DISABLE_EXPORT
free
CONFIG_NSH_DISABLE_FREE
get CONFIG_NET && CONFIG_NET_UDP && MTU >= 5581 CONFIG_NSH_DISABLE_GET
help5
CONFIG_NSH_DISABLE_HELP
hexdump   CONFIG_NSH_DISABLE_HEXDUMP
ifconfig CONFIG_NET && CONFIG_FS_PROCFS && !CONFIG_FS_PROCFS_EXCLUDE_NET CONFIG_NSH_DISABLE_IFCONFIG
ifdown CONFIG_NET && CONFIG_FS_PROCFS && !CONFIG_FS_PROCFS_EXCLUDE_NET CONFIG_NSH_DISABLE_IFUPDOWN
ifup CONFIG_NET && CONFIG_FS_PROCFS && !CONFIG_FS_PROCFS_EXCLUDE_NET CONFIG_NSH_DISABLE_IFUPDOWN
insmod CONFIG_MODULE CONFIG_NSH_DISABLE_MODCMDS
irqinfo !CONFIG_DISABLE_MOUNTPOINT && CONFIG_FS_PROCFS && CONFIG_SCHED_IRQMONITOR
kill   CONFIG_NSH_DISABLE_KILL
losetup !CONFIG_DISABLE_MOUNTPOINT && CONFIG_DEV_LOOP CONFIG_NSH_DISABLE_LOSETUP
ln CONFIG_PSEUDOFS_SOFTLINKS CONFIG_NSH_DISABLE_LN
ls   CONFIG_NSH_DISABLE_LS
lsmod CONFIG_MODULE && CONFIG_FS_PROCFS && !CONFIG_FS_PROCFS_EXCLUDE_MODULE CONFIG_NSH_DISABLE_MODCMDS
md5 CONFIG_NETUTILS_CODECS && CONFIG_CODECS_HASH_MD5 CONFIG_NSH_DISABLE_MD5
mb,mh,mw
CONFIG_NSH_DISABLE_MB,
CONFIG_NSH_DISABLE_MH,
CONFIG_NSH_DISABLE_MW
mkdir (((!CONFIG_DISABLE_MOUNTPOINT && CONFIG_FS_WRITABLE) || !CONFIG_DISABLE_PSEUDOFS_OPERATIONS) CONFIG_NSH_DISABLE_MKDIR
mkfatfs !CONFIG_DISABLE_MOUNTPOINT && CONFIG_FSUTILS_MKFATFS CONFIG_NSH_DISABLE_MKFATFS
mkfifo CONFIG_PIPES && CONFIG_DEV_FIFO_SIZE > 0 CONFIG_NSH_DISABLE_MKFIFO
mkrd !CONFIG_DISABLE_MOUNTPOINT && CONFIG_FS_WRITABLE4 CONFIG_NSH_DISABLE_MKRD
mount !CONFIG_DISABLE_MOUNTPOINT && CONFIG_FS_READABLE3 CONFIG_NSH_DISABLE_MOUNT
mv (!CONFIG_DISABLE_MOUNTPOINT && CONFIG_FS_WRITABLE) || !CONFIG_DISABLE_PSEUDOFS_OPERATIONS4 CONFIG_NSH_DISABLE_MV
nfsmount !CONFIG_DISABLE_MOUNTPOINT && CONFIG_NET && CONFIG_NFS CONFIG_NSH_DISABLE_NFSMOUNT
nslookup CONFIG_LIBC_NETDB && CONFIG_NETDB_DNSCLIENT CONFIG_NSH_DISABLE_NSLOOKUP
passwd !CONFIG_DISABLE_MOUNTPOINT && CONFIG_FS_WRITABLE && CONFIG_NSH_LOGIN_PASSWDsup>4 CONFIG_NSH_DISABLE_PASSWD
pmconfig CONFIG_PM CONFIG_NSH_DISABLE_PMCONFIG
poweroff CONFIG_BOARDCTL_POWEROFF CONFIG_NSH_DISABLE_POWEROFF
ps CONFIG_FS_PROCFS && !CONFIG_FS_PROCFS_EXCLUDE_PROC CONFIG_NSH_DISABLE_PS
put CONFIG_NET && CONFIG_NET_UDP && MTU >= 5581,2 CONFIG_NSH_DISABLE_PUT
pwd !CONFIG_DISABLE_ENVIRON CONFIG_NSH_DISABLE_PWD
readlink CONFIG_PSEUDOFS_SOFTLINKS CONFIG_NSH_DISABLE_READLINK
reboot CONFIG_BOARD_RESET CONFIG_NSH_DISABLE_REBOOT
rm (!CONFIG_DISABLE_MOUNTPOINT && CONFIG_FS_WRITABLE) || !CONFIG_DISABLE_PSEUDOFS_OPERATIONS4 CONFIG_NSH_DISABLE_RM
rmdir (!CONFIG_DISABLE_MOUNTPOINT && CONFIG_FS_WRITABLE) || !CONFIG_DISABLE_PSEUDOFS_OPERATIONS4 CONFIG_NSH_DISABLE_RMDIR
rmmod CONFIG_MODULE CONFIG_NSH_DISABLE_MODCMDS
route CONFIG_FS_PROCFS && CONFIG_FS_PROCFS_EXCLUDE_NET && !CONFIG_FS_PROCFS_EXCLUDE_ROUTE && CONFIG_NET_ROUTE && !CONFIG_NSH_DISABLE_ROUTE && (CONFIG_NET_IPv4 || CONFIG_NET_IPv6) CONFIG_NSH_DISABLE_ROUTE
rptun CONFIG_RPTUN CONFIG_NSH_DISABLE_RPTUN
set CONFIG_NSH_VARS || !CONFIG_DISABLE_ENVIRON CONFIG_NSH_DISABLE_SET
sh CONFIG_NFILE_STREAMS > 0 && !CONFIG_NSH_DISABLESCRIPT CONFIG_NSH_DISABLE_SH
shutdown CONFIG_BOARDCTL_POWEROFF || CONFIG_BOARD_RESET CONFIG_NSH_DISABLE_SHUTDOWN
sleep   CONFIG_NSH_DISABLE_SLEEP
telnetd CONFIG_NSH_TELNET CONFIG_NSH_DISABLE_TELNETD
test !CONFIG_NSH_DISABLESCRIPT CONFIG_NSH_DISABLE_TEST
time   CONFIG_NSH_DISABLE_TIME
truncate !CONFIG_DISABLE_MOUNTPOINT CONFIG_NSH_DISABLE_TRUNCATE
umount !CONFIG_DISABLE_MOUNTPOINT && CONFIG_FS_READABLE3 CONFIG_NSH_DISABLE_UMOUNT
uname   CONFIG_NSH_DISABLE_UNAME
unset CONFIG_NSH_VARS || !CONFIG_DISABLE_ENVIRON CONFIG_NSH_DISABLE_UNSET
urldecode !CONFIG_NETUTILS_CODECS && CONFIG_CODECS_URLCODE CONFIG_NSH_DISABLE_URLDECODE
urlencode !CONFIG_NETUTILS_CODECS && CONFIG_CODECS_URLCODE CONFIG_NSH_DISABLE_URLENCODE
useradd !CONFIG_DISABLE_MOUNTPOINT && CONFIG_FS_WRITABLE && CONFIG_NSH_LOGIN_PASSWDsup>4 CONFIG_NSH_DISABLE_USERADD
userdel !CONFIG_DISABLE_MOUNTPOINT && CONFIG_FS_WRITABLE && CONFIG_NSH_LOGIN_PASSWDsup>4 CONFIG_NSH_DISABLE_USERDEL
usleep   CONFIG_NSH_DISABLE_USLEEP
wget CONFIG_NET && CONFIG_NET_TCP CONFIG_NSH_DISABLE_WGET
xd
CONFIG_NSH_DISABLE_XD

1 Because of hardware padding, the actual required packet size may be larger
2 Special TFTP server start-up options will probably be required to permit creation of files for the correct operation of the put command.
3 CONFIG_FS_READABLE is not a user configuration but is set automatically if any readable file system is selected. At present, this is either CONFIG_FS_FAT or CONFIG_FS_ROMFS.
4 CONFIG_FS_WRITABLE is not a user configuration but is set automatically if any writable file system is selected. At present, this is only CONFIG_FS_FAT.
5 Verbose help output can be suppressed by defining CONFIG_NSH_HELP_TERSE. In that case, the help command is still available but will be slightly smaller.

4.2 Built-In Command Dependencies on Configuration Settings

All built-in applications require that support for NSH built-in applications has been enabled. This support is enabled with CONFIG_BUILTIN=y and CONFIG_NSH_BUILTIN_APPS=y.

Table. Built-In Command Dependencies on Configuration Settings

Command Depends on Configuration
ping CONFIG_NET && CONFIG_NET_ICMP && CONFIG_NET_ICMP_SOCKET && CONFIG_SYSTEM_PING
ping6 CONFIG_NET && CONFIG_NET_ICMPv6 && CONFIG_NET_ICMPv6_SOCKET && CONFIG_SYSTEM_PING6

4.3 NSH-Specific Configuration Settings

The behavior of NSH can be modified with the following settings in the boards/<arch>/<chip>/<board>/defconfig file:

Configuration Description
CONFIG_NSH_READLINE Selects the minimal implementation of readline(). This minimal implementation provides on backspace for command line editing. It expects some minimal VT100 command support from the terminal.
CONFIG_NSH_CLE Selects the more extensive, EMACS-like command line editor. Select this option only if (1) you don't mind a modest increase in the FLASH footprint, and (2) you work with a terminal that supports extensive VT100 editing commands. Selecting this option will add probably 1.5-2KB to the FLASH footprint.
CONFIG_NSH_BUILTIN_APPS Support external registered, "builtin" applications that can be executed from the NSH command line (see apps/README.txt for more information). This required CONFIG_BUILTIN to enable NuttX support for "builtin" applications.
CONFIG_NSH_FILEIOSIZE Size of a static I/O buffer used for file access (ignored if there is no file system). Default is 1024.
CONFIG_NSH_STRERROR strerror(errno) makes more readable output but strerror() is very large and will not be used unless this setting is y. This setting depends upon the strerror() having been enabled with CONFIG_LIBC_STRERROR.
CONFIG_NSH_LINELEN The maximum length of one command line and of one output line. Default: 80
CONFIG_NSH_DISABLE_SEMICOLON By default, you can enter multiple NSH commands on a line with each command separated by a semicolon. You can disable this feature to save a little memory on FLASH challenged platforms. Default: n
CONFIG_NSH_CMDPARMS If selected, then the output from commands, from file applications, and from NSH built-in commands can be used as arguments to other commands. The entity to be executed is identified by enclosing the command line in back quotes. For example,
    set FOO `myprogram $BAR`
    
will execute the program named myprogram passing it the value of the environment variable BAR. The value of the environment variable FOO is then set output of myprogram on stdout. Because this feature commits significant resources, it is disabled by default. The CONFIG_NSH_CMDPARMS interim output will be retained in a temporary file. Full path to a directory where temporary files can be created is taken from CONFIG_LIBC_TMPDIR and it defaults to /tmp if CONFIG_LIBC_TMPDIR is not set.
CONFIG_NSH_MAXARGUMENTS The maximum number of NSH command arguments. Default: 6
CONFIG_NSH_ARGCAT Support concatenation of strings with environment variables or command output. For example:
    set FOO XYZ
    set BAR 123
    set FOOBAR ABC_${FOO}_${BAR}
    
would set the environment variable FOO to XYZ, BAR to 123 and FOOBAR to ABC_XYZ_123. If CONFIG_NSH_ARGCAT is not selected, then a slightly small FLASH footprint results but then also only simple environment variables like $FOO can be used on the command line.
CONFIG_NSH_VARS By default, there are no internal NSH variables. NSH will use OS environment variables for all variable storage. If this option, NSH will also support local NSH variables. These variables are, for the most part, transparent and work just like the OS environment variables. The difference is that when you create new tasks, all of environment variables are inherited by the created tasks. NSH local variables are not.

If this option is enabled (and CONFIG_DISABLE_ENVIRON is not), then a new command called 'export' is enabled. The export command works very must like the set command except that is operates on environment variables. When CONFIG_NSH_VARS is enabled, there are changes in the behavior of certain commands

CMD w/o CONFIG_NSH_VARS w/ CONFIG_NSH_VARS
set <a> <b> Set environment variable <a> to <b> Set NSH variable <a> to <b> (Unless the NSH variable has been promoted via export, in which case the environment variable of the same name is set to <b>).
set Causes an error. Lists all NSH variables.
unset <a> Unsets environment variable <a> Unsets both environment variable and NSH variable with and name <a>
export <a> <b> Causes an error, Unsets NSH variable <a>. Sets environment variable <a> to <b>.
export <a> Causes an error. Sets environment variable <a> to the value of NSH variable <a> (or "" if the NSH variable has not been set). Unsets NSH local variable <a>.
env Lists all environment variables Lists all environment variables (only)
CONFIG_NSH_QUOTE Enables back-slash quoting of certain characters within the command. This option is useful for the case where an NSH script is used to dynamically generate a new NSH script. In that case, commands must be treated as simple text strings without interpretation of any special characters. Special characters such as $, `, ", and others must be retained intact as part of the test string. This option is currently only available is CONFIG_NSH_ARGCAT is also selected.
CONFIG_NSH_NESTDEPTH The maximum number of nested if-then[-else]-fi sequences that are permissible. Default: 3
CONFIG_NSH_DISABLESCRIPT This can be set to y to suppress support for scripting. This setting disables the sh, test, and [ commands and the if-then[-else]-fi construct. This would only be set on systems where a minimal footprint is a necessity and scripting is not.
CONFIG_NSH_DISABLE_ITEF If scripting is enabled, then then this option can be selected to suppress support for if-then-else-fi sequences in scripts. This would only be set on systems where some minimal scripting is required but if-then-else-fi is not.
CONFIG_NSH_DISABLE_LOOPS If scripting is enabled, then then this option can be selected suppress support for while-do-done and until-do-done sequences in scripts. This would only be set on systems where some minimal scripting is required but looping is not.
CONFIG_NSH_DISABLEBG This can be set to y to suppress support for background commands. This setting disables the nice command prefix and the & command suffix. This would only be set on systems where a minimal footprint is a necessity and background command execution is not.
CONFIG_NSH_MMCSDMINOR If the architecture supports an MMC/SD slot and if the NSH architecture specific logic is present, this option will provide the MMC/SD minor number, i.e., the MMC/SD block driver will be registered as /dev/mmcsdN where N is the minor number. Default is zero.
CONFIG_NSH_ROMFSETC Mount a ROMFS file system at /etc and provide a startup script at /etc/init.d/rcS. The default startup script will mount a FAT FS RAMDISK at /tmp but the logic is easily extensible.
CONFIG_NSH_CONSOLE

If CONFIG_NSH_CONSOLE is set to y, then a serial console front-end is selected.

Normally, the serial console device is a UART and RS-232 interface. However, if CONFIG_USBDEV is defined, then a USB serial device may, instead, be used if the one of the following are defined:

  • CONFIG_PL2303 and CONFIG_PL2303_CONSOLE. Sets up the Prolifics PL2303 emulation as a console device at /dev/console.
  • CONFIG_CDCACM and CONFIG_CDCACM_CONSOLE. Sets up the CDC/ACM serial device as a console device at /dev/console.
  • CONFIG_NSH_USBCONSOLE. If defined, then an arbitrary USB device may be used to as the NSH console. In this case, CONFIG_NSH_USBCONDEV must be defined to indicate which USB device to use as the console. The advantage of using a device other that /dev/console is that normal debug output can then use /dev/console while NSH uses CONFIG_NSH_USBCONDEV.

    CONFIG_NSH_USBCONDEV. If CONFIG_NSH_USBCONSOLE is set to 'y', then CONFIG_NSH_USBCONDEV must also be set to select the USB device used to support the NSH console. This should be set to the quoted name of a readable/write-able USB driver such as: CONFIG_NSH_USBCONDEV="/dev/ttyACM0".

If there are more than one USB slots, then a USB device minor number may also need to be provided:

  • CONFIG_NSH_UBSDEV_MINOR. The minor device number of the USB device. Default: 0

If USB tracing is enabled (CONFIG_USBDEV_TRACE), then NSH will initialize USB tracing as requested by the following. Default: Only USB errors are traced.

  • CONFIG_NSH_USBDEV_TRACEINIT. Show initialization events
  • CONFIG_NSH_USBDEV_TRACECLASS. Show class driver events
  • CONFIG_NSH_USBDEV_TRACETRANSFERS. Show data transfer events
  • CONFIG_NSH_USBDEV_TRACECONTROLLER. Show controller events
  • CONFIG_NSH_USBDEV_TRACEINTERRUPTS. Show interrupt-related events.
CONFIG_NSH_ALTCONDEV and CONFIG_NSH_CONDEV If CONFIG_NSH_CONSOLE is set to y, then CONFIG_NSH_ALTCONDEV may also be selected to enable use of an alternate character device to support the NSH console. If CONFIG_NSH_ALTCONDEV is selected, then CONFIG_NSH_CONDEV holds the quoted name of a readable/write-able character driver such as: CONFIG_NSH_CONDEV="/dev/ttyS1". This is useful, for example, to separate the NSH command line from the system console when the system console is used to provide debug output. Default: stdin and stdout (probably "/dev/console")
  • NOTE 1: When any other device other than /dev/console is used for a user interface, (1) linefeeds (\n) will not be expanded to carriage return / linefeeds (\r\n). You will need to configure your terminal program to account for this. And (2) input is not automatically echoed so you will have to turn local echo on.
  • NOTE 2: This option forces the console of all sessions to use NSH_CONDEV. Hence, this option only makes sense for a system that supports only a single session. This option is, in particular, incompatible with Telnet sessions because each Telnet session must use a different console device.
CONFIG_NSH_TELNET If CONFIG_NSH_TELNET is set to y, then a TELNET server front-end is selected. When this option is provided, you may log into NuttX remotely using telnet in order to access NSH.
CONFIG_NSH_ARCHINIT Set CONFIG_NSH_ARCHINIT if your board provides architecture specific initialization via the board-specific function board_app_initialize(). This function will be called early in NSH initialization to allow board logic to do such things as configure MMC/SD slots.

If Telnet is selected for the NSH console, then we must configure the resources used by the Telnet daemon and by the Telnet clients.

Configuration Description
CONFIG_NSH_TELNETD_PORT The telnet daemon will listen on this TCP port number for connections. Default: 23
CONFIG_NSH_TELNETD_DAEMONPRIO Priority of the Telnet daemon. Default: SCHED_PRIORITY_DEFAULT
CONFIG_NSH_TELNETD_DAEMONSTACKSIZE Stack size allocated for the Telnet daemon. Default: 2048
CONFIG_NSH_TELNETD_CLIENTPRIO Priority of the Telnet client. Default: SCHED_PRIORITY_DEFAULT
CONFIG_NSH_TELNETD_CLIENTSTACKSIZE Stack size allocated for the Telnet client. Default: 2048

One or both of CONFIG_NSH_CONSOLE and CONFIG_NSH_TELNET must be defined. If CONFIG_NSH_TELNET is selected, then there some other configuration settings that apply:

Configuration Description
CONFIG_NET=y Of course, networking must be enabled.
CONFIG_NSOCKET_DESCRIPTORS And, of course, you must allocate some socket descriptors.
CONFIG_NET_TCP=y TCP/IP support is required for telnet (as well as various other TCP-related configuration settings).
CONFIG_NSH_IOBUFFER_SIZE Determines the size of the I/O buffer to use for sending/ receiving TELNET commands/responses
CONFIG_NSH_DHCPC Obtain the IP address via DHCP.
CONFIG_NSH_IPADDR If CONFIG_NSH_DHCPC is NOT set, then the static IP address must be provided.
CONFIG_NSH_DRIPADDR Default router IP address
CONFIG_NSH_NETMASK Network mask
CONFIG_NSH_NOMAC Set if your Ethernet hardware has no built-in MAC address. If set, a bogus MAC will be assigned.
CONFIG_NSH_MAX_ROUNDTRIP This is the maximum round trip for a response to a ICMP ECHO request. It is in units of deciseconds. The default is 20 (2 seconds).

If you use DHCPC, then some special configuration network options are required. These include:

Configuration Description
CONFIG_NET=y Of course, networking must be enabled.
CONFIG_NSOCKET_DESCRIPTORS And, of course, you must allocate some socket descriptors.
CONFIG_NET_UDP=y UDP support is required for DHCP (as well as various other UDP-related configuration settings).
CONFIG_NET_BROADCAST=y UDP broadcast support is needed.
CONFIG_NET_ETH_PKTSIZE=650 (or larger) Per RFC2131 (p. 9), the DHCP client must be prepared to receive DHCP messages of up to 576 bytes (excluding Ethernet, IP, or UDP headers and FCS). NOTE: Note that the actual MTU setting will depend upon the specific link protocol. Here Ethernet is indicated.

If CONFIG_NSH_ROMFSETC is selected, then the following additional configuration setting apply:

Configuration Description
CONFIG_NSH_ARCHROMFS May be defined to specify an alternative ROMFS image that can be found at boards/<arch>/<chip>/<board>/include/nsh_romfsimg.h.
CONFIG_NSH_ROMFSMOUNTPT The default mountpoint for the ROMFS volume is "/etc", but that can be changed with this setting. This must be a absolute path beginning with '/' and enclosed in quotes.
CONFIG_NSH_INITSCRIPT This is the relative path to the startup script within the mountpoint. The default is "init.d/rcS". This is a relative path and must not start with '/' but must be enclosed in quotes.
CONFIG_NSH_ROMFSDEVNO This is the minor number of the ROMFS block device. The default is '0' corresponding to /dev/ram0.
CONFIG_NSH_ROMFSSECTSIZE This is the sector size to use with the ROMFS volume. Since the default volume is very small, this defaults to 64 but should be increased if the ROMFS volume were to be become large. Any value selected must be a power of 2.

When the default rcS file used when CONFIG_NSH_ROMFSETC is selected, it will mount a FAT FS under /tmp. The following selections describe that FAT FS.

Configuration Description
CONFIG_NSH_FATDEVNO This is the minor number of the FAT FS block device. The default is '1' corresponding to /dev/ram1.
CONFIG_NSH_FATSECTSIZE This is the sector size use with the FAT FS. Default is 512.

5.0 Customizing the NuttShell

Overview. The NuttShell (NSH) is a simple shell application that may be used with NuttX. It supports a variety of commands and is (very) loosely based on the Bash shell and the common utilities used with Bash shell programming. The paragraphs in this appendix will focus on customizing NSH: Adding new commands, changing the initialization sequence, etc.

5.1 The NSH Library and NSH Initialization

Overview. NSH is implemented as a library that can be found at apps/nshlib. As a library, it can be custom built into any application that follows the NSH initialization sequence described below. As an example, the code at apps/examples/nsh/nsh_main.c illustrates how to start NSH and the logic there was intended to be incorporated into your own custom code. Although code was generated simply as an example, in the end most people just use this example code as their application main() function. That initialization performed by that example is discussed in the following paragraphs.

5.1.1 NSH Initialization sequence

The NSH start-up sequence is very simple. As an example, the code at apps/examples/nsh/nsh_main.c illustrates how to start NSH. It simple does the following:

  1. If you have C++ static initializers, it will call your implementation of up_cxxinitialize() which will, in turn, call those static initializers. For the case of the STM3240G-EVAL board, the implementation of up_cxxinitialize() can be found at nuttx/boards/arm/stm32/stm3240g-eval/src/up_cxxinitialize.c.

  2. This function then calls nsh_initialize() which initializes the NSH library. nsh_initialize() is described in more detail below.

  3. If the Telnetconsole is enabled, it calls nsh_telnetstart() which resides in the NSH library. nsh_telnetstart() will start the Telnet daemon that will listen for Telnet connections and start remote NSH sessions.

  4. If a local console is enabled (probably on a serial port), then nsh_consolemain() is called. nsh_consolemain() also resides in the NSH library. nsh_consolemain() does not return so that finished the entire NSH initialization sequence.

5.1.2 nsh_initialize()

The NSH initialization function, nsh_initialize(), be found in apps/nshlib/nsh_init.c. It does only three things:

  1. nsh_romfsetc(): If so configured, it executes an NSH start-up script that can be found at /etc/init.d/rcS in the target file system. The nsh_romfsetc() function can be found in apps/nshlib/nsh_romfsetc.c. This function will (1) register a ROMFS file system, then (2) mount the ROMFS file system. /etc is the default location where a read-only, ROMFS file system is mounted by nsh_romfsetc().

    The ROMFS image is, itself, just built into the firmware. By default, this rcS start-up script contains the following logic:

      # Create a RAMDISK and mount it at XXXRDMOUNTPOINTXXX
      
      mkrd -m XXXMKRDMINORXXX -s XXMKRDSECTORSIZEXXX XXMKRDBLOCKSXXX
      mkfatfs /dev/ramXXXMKRDMINORXXX
      mount -t vfat /dev/ramXXXMKRDMINORXXX XXXRDMOUNTPOINTXXX
      

    Where the XXXX*XXXX strings get replaced in the template when the ROMFS image is created:

    • XXXMKRDMINORXXX will become the RAM device minor number. Default: 0

    • XXMKRDSECTORSIZEXXX will become the RAM device sector size

    • XXMKRDBLOCKSXXX will become the number of sectors in the device.

    • XXXRDMOUNTPOINTXXX will become the configured mount point. Default: /etc

    By default, the substituted values would yield an rcS file like:

      # Create a RAMDISK and mount it at /tmp
      
      mkrd -m 1 -s 512 1024
      mkfatfs /dev/ram1
      mount -t vfat /dev/ram1 /tmp
      

    This script will, then:

    • Create a RAMDISK of size 512*1024 bytes at /dev/ram1,

    • Format a FAT file system on the RAM disk at /dev/ram1, and then

    • Mount the FAT file system at a configured mountpoint, /tmp.

    This rcS template file can be found at apps/nshlib/rcS.template. The resulting ROMFS file system can be found in apps/nshlib/nsh_romfsimg.h.

  2. board_app_initialize(): Next any architecture-specific NSH initialization will be performed (if any). For the STM3240G-EVAL, this architecture specific initialization can be found at boards/arm/stm32/stm3240g-eval/src/stm32_appinit.c. This it does things like: (1) Initialize SPI devices, (2) Initialize SDIO, and (3) mount any SD cards that may be inserted.

  3. nsh_netinit(): The nsh_netinit() function can be found in apps/nshlib/nsh_netinit.c.

5.2 NSH Commands

Overview. NSH supports a variety of commands as part of the NSH program. All of the NSH commands are listed in the NSH documentation above. Not all of these commands may be available at any time, however. Many commands depend upon certain NuttX configuration options. You can enter the help command at the NSH prompt to see the commands actual available:

For example, if network support is disabled, then all network-related commands will be missing from the list of commands presented by 'nsh> help'. You can see the specific command dependencies in the table above.

5.2.1 Adding New NSH Commands

New commands can be added to the NSH very easily. You simply need to add two things:

  1. The implementation of your command, and

  2. A new entry in the NSH command table

Implementation of Your Command. For example, if you want to add a new a new command called mycmd to NSH, you would first implement the mycmd code in a function with this prototype:

The argc and argv are used to pass command line arguments to the NSH command. Command line parameters are passed in a very standard way: argv[0] will be the name of the command, and argv[1] through argv[argc-1] are the additional arguments provided on the NSH command line.

The first parameter, vtbl, is special. This is a pointer to session-specific state information. You don't need to know the contents of the state information, but you do need to pass this vtbl argument when you interact with the NSH logic. The only use you will need to make of the vtbl argument will be for outputting data to the console. You don't use printf() within NSH commands. Instead you would use:

So if you only wanted to output "Hello, World!" on the console, then your whole command implementation might be:

The prototype for the new command should be placed in apps/examples/nshlib/nsh.h.

Adding You Command to the NSH Command Table. All of the commands support by NSH appear in a single table called:

That table can be found in the file apps/examples/nshlib/nsh_parse.c. The structure cmdmap_s is also defined in apps/nshlib/nsh_parse.c:

This structure provides everything that you need to describe your command: Its name (cmd), the function that handles the command (cmd_mycmd()), the minimum and maximum number of arguments needed by the command, and a string describing the command line arguments. That last string is what is printed when enter "nsh> help".

So, for you sample command, you would add the following the to the g_cmdmap[] table:

This entry is particularly simply because mycmd is so simple. Look at the other commands in g_cmdmap[] for more complex examples.

5.3 NSH "Built-In" Applications

Overview. In addition to these commands that are a part of NSH, external programs can also be executed as NSH commands. These external programs are called "Built-In" Applications for historic reasons. That terminology is somewhat confusing because the actual NSH commands as described above are truly "built-into" NSH whereas these applications are really external to NuttX.

These applications are built-into NSH in the sense that they can be executed by simply typing the name of the application at the NSH prompt. Built-in application support is enabled with these configuration option:

When these configuration options are set, you will also be able to see the built-in applications if you enter "nsh> help". They will appear at the bottom of the list of NSH commands under:

Note that no detailed help information beyond the name of the built-in application is provided.

5.3.1 Built-In Applications

Overview. The underlying logic that supports the NSH built-in applications is called "Built-In Applications". The builtin application logic can be found at apps/builtin. This logic simply does the following:

  1. It supports registration mechanism so that builtin applications can dynamically register themselves at build time, and

  2. Utility functions to look up, list, and execute the builtin applications.

Built-In Application Utility Functions. The utility functions exported by the builtin application logic are prototyped in nuttx/include/nuttx/lib/builtin.h and apps/include/builtin.h. These utility functions include:

Autogenerated Header Files. Application entry points with their requirements are gathered together in two files when NuttX is first built:

  1. apps/builtin/builtin_proto.h: Prototypes of application task entry points.

  2. apps/builtin/builtin_list.h: Application specific information and start-up requirements

Registration of Built-In Applications. The NuttX build occurs in several phases as different build targets are executed: (1) context when the configuration is established, (2) depend when target dependencies are generated, and (3) default (all) when the normal compilation and link operations are performed. Built-in application information is collected during the make context build phase.

An example application that can be "built-in" is be found in the apps/examples/hello directory. Let's walk through this specific cause to illustrate the general way that built-in applications are created and how they register themselves so that they can be used from NSH.

apps/examples/hello. The main routine for apps/examples/hello can be found in apps/examples/hello/main.c. The main routine is:

This is the built in function that will be registered during the context build phase of the NuttX build. That registration is performed by logic in apps/examples/hello/Makefile. But the build system gets to that logic through a rather tortuous path:

  1. The top-level context make target is in nuttx/Makefile. All build targets depend upon the context build target. For the apps/ directory, this build target will execute the context target in the apps/Makefile.

  2. The apps/Makefile will, in turn, execute the context targets in all of the configured sub-directories. In our case will include the Makefile in apps/examples.

  3. And finally, the apps/examples/Makefile will execute the context target in all configured examplesub-directories, getting us finally to apps/examples/Makefile which is covered below.

NOTE: Since this context build phase can only be executed one time, any subsequent configuration changes that you make will, then, not be reflected in the build sequence. That is a common area of confusion. Before you can instantiate the new configuration, you have to first get rid of the old configuration. The most drastic way to this is:

But then you will have to re-configuration NuttX from scratch. But if you only want to re-build the configuration in the apps/ sub-directory, then there is a less labor-intensive way to do that. The following NuttX make command will remove the configuration only from the apps/ directory and will let you continue without re-configuring everything:

Logic for the context target in apps/examples/hello/Makefile registers the hello_main() application in the builtin's builtin_proto.hand builtin_list.h files. That logic that does that in apps/examples/hello/Makefile is abstracted below:

  1. First, the Makefile includes apps/Make.defs:

      include $(APPDIR)/Make.defs
      

    This defines a macro called REGISTER that adds data to the builtin header files:

      define REGISTER
          @echo "Register: $1"
          @echo "{ \"$1\", $2, $3, $4 }," >> "$(APPDIR)/builtin/builtin_list.h"
          @echo "EXTERN int $4(int argc, char *argv[]);" >> "$(APPDIR)/builtin/builtin_proto.h"
      endef
      

    When this macro runs, you will see the output in the build "Register: hello", that is a sure sign that the registration was successful.

  2. The make file then defines the application name (hello), the task priority (default), and the stack size that will be allocated in the task runs (2K).

      APPNAME         = hello
      PRIORITY        = SCHED_PRIORITY_DEFAULT
      STACKSIZE       = 2048
      
  3. And finally, the Makefile invokes the REGISTER macro to added the hello_main() builtin application. Then, when the system build completes, the hello command can be executed from the NSH command line. When the hello command is executed, it will start the task with entry point hello_main() with the default priority and with a stack size of 2K.

      context:
        $(call REGISTER,$(APPNAME),$(PRIORITY),$(STACKSIZE),$(APPNAME)_main)
      

Other Uses of Built-In Application. The primary purpose of builtin applications is to support command line execution of applications from NSH. However, there is one other use of builtin applications that should be mentioned.

  1. binfs. binfs is a tiny file system located at apps/builtin/binfs.c. This provides an alternative what of visualizing installed builtin applications. Without binfs, you can see the installed builtin applications using the NSH help command. binfs will create a tiny pseudo-file system mounted at /bin. Using binfs, you can see the available builtin applications by listing the contents of /bin directory. This gives some superficial Unix-like compatibility, but does not really add any new functionality.

5.3.2 Synchronous Built-In Applications

By default, built-in commands started from the NSH command line will run asynchronously with NSH. If you want to force NSH to execute commands then wait for the command to execute, you can enable that feature by adding the following to the NuttX configuration file:

This configuration option enables support for the standard waitpid() RTOS interface. When that interface is enabled, NSH will use it to wait, sleeping until the built-in application executes to completion.

Of course, even with CONFIG_SCHED_WAITPID=y defined, specific applications can still be forced to run asynchronously by adding the ampersand (&) after the NSH command.

5.4 Customizing NSH Initialization

Ways to Customize NSH Initialization. There are three ways to customize the NSH start-up behavior. Here they are presented in order of increasing difficulty:

  1. You can extend the initialization logic in boards/arm/stm32/stm3240g-eval/src/stm32_appinit.c. The logic there is called each time that NSH is started and is good place in particular for any device-related initialization.

  2. You replace the sample code at apps/examples/nsh/nsh_main.c with whatever start-up logic that you want. NSH is a library at apps/nshlib. apps.examples/nsh is just a tiny, example start-up function (CONFIG_USER_ENTRYPOINT()) that that runs immediately and illustrates how to start NSH If you want something else to run immediately then you can write your write your own custom CONFIG_USER_ENTRYPOINT() function and then start other tasks from your custom CONFIG_USER_ENTRYPOINT().

  3. NSH also supports a start-up script that executed when NSH first runs. This mechanism has the advantage that the start-up script can contain any NSH commands and so can do a lot of work with very little coding. The disadvantage is that is is considerably more complex to create the start-up script. It is sufficiently complex that is deserves its own paragraph

5.4.1 NuttShell Start up Scripts

First of all you should look at NSH Start-Up Script paragraph. Most everything you need to know can be found there. That information will be repeated and extended here for completeness.

NSH Start-Up Script. NSH supports options to provide a start up script for NSH. The start-up script contains any command support by NSH (i.e., that you see when you enter 'nsh> help'). In general this capability is enabled with CONFIG_NSH_ROMFSETC=y, but has several other related configuration options as described with the NSH-specific configuration settings paragraph. This capability also depends on:

Default Start-Up Behavior. The implementation that is provided is intended to provide great flexibility for the use of Start-Up files. This paragraph will discuss the general behavior when all of the configuration options are set to the default values.

In this default case, enabling CONFIG_NSH_ROMFSETC will cause NSH to behave as follows at NSH start-up time:

Example Configurations. Here are some configurations that have CONFIG_NSH_ROMFSETC=y in the NuttX configuration file. They might provide useful examples:

In most of these cases, the configuration sets up the default /etc/init.d/rcS script. The default script is here: apps/nshlib/rcS.template. (The funny values in the template like XXXMKRDMINORXXX get replaced via sed at build time). This default configuration creates a ramdisk and mounts it at /tmp as discussed above.

If that default behavior is not what you want, then you can provide your own custom rcS script by defining CONFIG_NSH_ARCHROMFS=y in the configuration file.

Modifying the ROMFS Image. The contents of the /etc directory are retained in the file apps/nshlib/nsh_romfsimg.h OR, if CONFIG_NSH_ARCHROMFS is defined, include/arch/board/nsh_romfsimg.h. In order to modify the start-up behavior, there are three things to study:

  1. Configuration Options. The additional CONFIG_NSH_ROMFSETC configuration options discussed with the other NSH-specific configuration settings.

  2. tools/mkromfsimg.sh Script. The script tools/mkromfsimg.sh creates nsh_romfsimg.h. It is not automatically executed. If you want to change the configuration settings associated with creating and mounting the /tmp directory, then it will be necessary to re-generate this header file using the tools/mkromfsimg.sh script.

    The behavior of this script depends upon several things:

    1. The configuration settings then installed configuration.

    2. The genromfs tool(available from http://romfs.sourceforge.net) or included within the NuttX buildroot toolchain. There is also a snapshot available in the NuttX tools repository here.

    3. The xxd tool that is used to generate the C header files (xxd is a normal part of a complete Linux or Cygwin installation, usually as part of the vi package).

    4. The file apps/nshlib/rcS.template (OR, if CONFIG_NSH_ARCHROMFS is defined include/arch/board/rcs.template.

  3. rcS.template. The file apps/nshlib/rcS.template contains the general form of the rcS file; configured values are plugged into this template file to produce the final rcS file.

    To generate a custom rcS file a copy of rcS.template needs to be placed at tools/ and changed according to the desired start-up behaviour. Running tools/mkromfsimg.h creates nsh_romfsimg.h which needs to be copied to apps/nshlib OR if CONFIG_NSH_ARCHROMFS is defined to boards/<arch>/<chip>/<board>/include.

rcS.template. The default rcS.template, apps/nshlib/rcS.template, generates the standard, default apps/nshlib/nsh_romfsimg.h file.

If CONFIG_NSH_ARCHROMFS is defined in the NuttX configuration file, then a custom, board-specific nsh_romfsimg.h file residing in boards/<arch>/<chip>/<board>/includewill be used. NOTE when the OS is configured, include/arch/board will be linked to boards/<arch>/<chip>/<board>/include.

All of the startup-behavior is contained in rcS.template. The role of mkromfsimg.sh script is to (1) apply the specific configuration settings to rcS.template to create the final rcS, and (2) to generate the header file nsh_romfsimg.h containing the ROMFS file system image. To do this, mkromfsimg.sh uses two tools that must be installed in your system:

  1. The genromfs tool that is used to generate the ROMFS file system image.

  2. The xxd tool that is used to create the C header file.

6.0 Shell Login

6.1 Enabling Shell Logins

NuttShell sessions can be protected by requiring that the user supply username and password credentials at the beginning of the session. Logins can be enabled for standard USB or serial consoles with:

Logins for Telnet sessions can be enabled separately with:

Logins can be enabled for either or both session types. On a successful login, the user will have access to the NSH session:

After each failed login attempt, a delay can be set up. The purpose of this delay is to discourage attempts to crack the password by brute force. That delay is configured with

This setting provides the login failure delay in units of milliseconds. The system will pause this amount of time after each failed login attempt. After a certain number of failed login attempts, the session will be closed. That number is controlled by:

6.2 Verification of Credentials

There are three ways that NSH can be configured to verify user credentials at login time:

  1. The simplest implementation simply uses fixed login credentials and is selected with:

      CONFIG_NSH_LOGIN_FIXED=y
      

    The fixed login credentials are selected via:

      CONFIG_NSH_LOGIN_USERNAME=admin
      CONFIG_NSH_LOGIN_PASSWORD="Administrator"
      

    This is not very flexible since there can be only one user and the password is fixed in the FLASH image. This option is also not very secure because a malicious user could get the password by just looking at the .text stings in the flash image.

  2. NSH can also be configured to defer the entire user credential verification to platform-specific logic with this setting:

      CONFIG_NSH_LOGIN_PLATFORM=y
      

    In this case, NSH will call a platform-specific function to perform the verification of user credentials. The platform-specific logic must provide a function with the following prototype:

      int platform_user_verify(FAR const char *username, FAR const char *password);
      

    which is prototyped an described in apps/include/nsh.h and which may be included like:

      #include <apps/nsh.h>
      

    An appropriate place to implement this function might be in the directory apps/platform/<board>.

  3. A final option is to use a password file contained encrypted password information. This final option is selected with the following and described in more detail in the following paragraph.

      CONFIG_NSH_LOGIN_PASSWD=y
      

6.3 Password Files

NuttX can also be configured to support a password file, by default at /etc/passwd. This option enables support for a password file:

This options requires that you have selected CONFIG_FSUTILS_PASSWD=y to enable the access methods of apps/fsutils/passwd:

And this determines the location of the password file in a mounted volume:

/etc/passwd is a standard location, but you will need to locate the password where ever you have a mounted volume.

The password file can be a fixed list of users in a ROMFS file system or a modifiable list maintained in a file in some writable file system. If the password file lies in a read-only file system like ROMFS, then you should also indicate that the password file is read-only.

If the password file is writable, then additional NSH commands will be enabled to modify the password file: useradd, userdel, and passwd. If you do not wish you have these commands available, then they should be specifically disabled.

The password file logic requires a few additional settings:

  1. The size of dynamically allocated and freed buffer that is used for file access:

      CONFIG_FSUTILS_PASSWD_IOBUFFER_SIZE=512
      
  2. And the 128-bit encryption key. The password file currently uses the Tiny Encryption Algorithm (TEA), but could be extended to use something more powerful.

      CONFIG_FSUTILS_PASSWD_KEY1=0x12345678
      CONFIG_FSUTILS_PASSWD_KEY2=0x9abcdef0
      CONFIG_FSUTILS_PASSWD_KEY3=0x12345678
      CONFIG_FSUTILS_PASSWD_KEY4=0x9abcdef0
      

Password can only be decrypted with access to this key. Note that this key could potentially be fished out of your FLASH image, but without any symbolic information, that would be a difficult job since the TEA KEY is binary data and not distinguishable from other binary data in the FLASH image.

If the password file is enabled (CONFIG_NSH_LOGIN_PASSWD=y), then the fixed user credentials will not be used for the NSH session login. Instead, the password file will be consulted to verify the user credentials.

6.4 Creating a Password File for a ROMFS File System

What we want to accomplish is a ROMFS file system, mounted at /etc and containing the password file, passwd like:

Where /etc/init.d/rcS is the start-up script; /etc/passwd is a the password file. Note that here we assume that you are already using a start-up script. We can then piggyback the passwd file into the /etc file system already mounted for the NSH start up file as described above above.

I use the sim/nsh configuration to create a new password file, but other configurations could also be used. That configuration already supports a ROMFS file system, passwords, and login prompts. First, I make these changes to that configuration.

  1. Disable logins

      - CONFIG_NSH_CONSOLE_LOGIN=y
      + # CONFIG_NSH_CONSOLE_LOGIN is not set
        # CONFIG_NSH_TELNET_LOGIN is not set
      
  2. Move the password file to a write-able file system:

      - CONFIG_FSUTILS_PASSWD_PATH="/etc/passwd"
      + CONFIG_FSUTILS_PASSWD_PATH="/tmp/passwd"
      
  3. Make the password file modifiable

      - CONFIG_FSUTILS_PASSWD_READONLY=y
      # CONFIG_FSUTILS_PASSWD_READONLY is not set
      

Now rebuild the simulation. No login should be required to enter the shell and you should find the useradd, userdel, and passwd commands available in the help summary, provided that they are enabled. Make certain that the useradd command is not disabled:

Use the NSH useradd command to add new uses with new user passwords like:

Do this as many times as you would like. Each time that you do this a new entry with an encrypted password will be added to the passwd file at /tmp/passwd. You can see the content of the password file like:

When you are finished, you can simply copy the /tmp/passwd content from the cat command and paste it into an editor. Make sure to remove any carriage returns that may have ended up on the file if you are using Windows.

Then create/re-create the nsh_romfsimg.h file as described below.

  1. The content on the nsh_romfsimg.h header file is generated from a template directory structure. Create the directory structure:

      mkdir etc
      mkdir etc/init.d
      

    And copy your existing startup script into etc/init.c as rcS.

  2. Save your new password file in the etc/ directory as passwd.

  3. Create the new ROMFS image.

      genromfs -f romfs_img -d etc -V MyVolName
      
  4. Convert the ROMFS image to a C header file

      xxd -i romfs_img >nsh_romfsimg.h
      
  5. Edit nsh_romfsimg.h: Mark both data definitions as const so that the data will be stored in FLASH.

  6. Edit nsh_romfsimg.h, mark both data definitions as const so that that will be stored in FLASH.

There is a good example of how to do this in the NSH simulation configuration at boards/sim/sim/sim/configs/nsh. The ROMFS support files are provided at boards/sim/include and the README.txt file at the location provides detailed information about creating and modifying the ROMFS file system.

Index