Command Line Interface
Introduction
Manual Compatibility
Manual Content
This manual provides a complete list of available console commands for Advantech routers. Commands are grouped into the following categories based on their usage:
- HW Control Commands.
- File/Directory Management Commands
- System Commands
- Network Commands
- Scripting/Shell Commands
Warning
You may find some commands available on the system that are not documented in this manual. These commands are not intended for regular user operations, and their incorrect use may cause system malfunction.
Command Line Access
The command-line interface (CLI) is a non-GUI alternative that allows you to manage the router. It provides an interactive interface enabling you to perform advanced configurations and troubleshoot the device directly.
SSH Connection
You can use an SSH (Secure Shell) connection to access the router’s console. A commonly used application for this is PuTTY. To connect securely without requiring credentials, you can use Passwordless Console Login with a public key.
Note: Ensure that SSH is enabled under Configuration → Services → SSH, refer to SSH.
Web Terminal Router App
The Web Terminal Router App allows you to access the router's console directly from the web GUI. This Router App is available for free on the Engineering Portal.
Permissions Notes
Please note that only a user with the admin role is permitted to access the router's console; a user with the user role does not have this access.
Commands that modify device status or configuration require privileged mode. When you log in to the console on the flexible platform, you are already in privileged mode, indicated by the # symbol on the prompt line.
Commands Introduction
In the vast and complex ecosystem of Unix-like operating systems, commands serve as the essential tools through which users interact with the system, automate tasks, manage resources, and configure services. Whether you are a system administrator, a network engineer, or a software developer, understanding and mastering these commands is crucial to effectively harnessing the full potential of the system.
This chapter delves into an array of commands integral to daily operations and specialized tasks alike. From scripting and shell command essentials that form the backbone of system automation and task scheduling, to administration commands that ensure system security and integrity, each command is a piece of the larger puzzle of system management. Network commands provide the keys to configuring, analyzing, and securing network communications, while router management commands focus on the specifics of networking device configuration. Additionally, file and directory management commands offer the means to navigate and manipulate the filesystem, ensuring data organization and accessibility. Lastly, the text processing and analysis commands section reveals the power of Unix-like systems in handling textual data, enabling the user to edit, search, and process text in various complex ways.
Structured to cater to both novice users seeking foundational knowledge and advanced users aiming to refine their expertise, this chapter aims to equip you with the understanding and practical know-how needed to navigate the intricacies of Unix-like operating systems with confidence. Through concise descriptions, usage examples, and categorized presentation, we invite you on a journey to mastery over your system's capabilities, one command at a time.
HW Control Commands
These commands are specific to router and network device management, offering functionalities to configure interfaces, manage routing tables, and control device-specific features.
cdmaat
💡 This command is not supported by routers of v1 production line.
This command interfaces with a CDMA module to send AT commands, facilitating direct communication and control over the module's functionality. This utility is especially useful for developers and administrators working with CDMA technology for diagnostics, configuration, or testing purposes.
Synopsis:
cdmaat <AT command>cdmaat sends specified AT commands to the connected CDMA module, allowing for a wide range of actions, from querying the module status to configuring its settings. The command's ability to interact directly with the CDMA module makes it a powerful tool for advanced device management.
Examples:
Check the signal quality of the CDMA module:
cdmaat AT+CSQReset the CDMA module:
cdmaat ATZcdmapwr
💡 This command is not supported by routers of v1 production line.
This command controls the power supply to the CDMA module, enabling or disabling it as required. This command is crucial for managing the module's power state, especially for conserving energy or resetting the module.
Synopsis:
cdmapwr [on | off]Description:
By specifying on or off, the cdmapwr command toggles the power state of the CDMA module. Turning the module off can be particularly useful for saving battery life in portable devices or when the module is not in use. Conversely, powering on the module restores its operational state, ready for communication or configuration.
Examples:
# Power on the CDMA module
cdmapwr on
# Power off the CDMA module
cdmapwr offgsminfo
This command retrieves and displays detailed information about the cellular module's status, including signal quality, network registration, and connection details. It is invaluable for diagnosing connectivity issues and optimizing signal reception.
Synopsis:
gsminfogsminfo provides a concise overview of the current cellular module's status, including the signal strength, network operator, and the communication channel. This information aids in assessing the quality of the connection and troubleshooting network problems.
Output Fields:
| Field | Description |
|---|---|
Manufacturer | Cellular module manufacturer. |
Model | Cellular module model designation. |
Revision | Firmware revision of the cellular module. |
IMEI | International Mobile Equipment Identity number. |
ICCID | Integrated Circuit Card Identifier of the active SIM card. |
IMSI | International Mobile Subscriber Identity of the active SIM card. |
Registration | Current network registration status. |
Operator | Name of the mobile network operator. |
Technology | Active cellular technology (e.g., LTE, 5G). |
PLMN | Public Land Mobile Network code of the operator. |
Cell | Identifier of the currently connected cell. |
Channel | Channel number used for communication. |
Band | Active cellular frequency band. |
Signal Strength | Signal strength of the connected cell (dBm). |
Signal Quality | Signal quality of the connected cell (dB). |
RSSI | Received Signal Strength Indicator (dBm). |
RSRP | Reference Signal Received Power (dBm). |
RSRQ | Reference Signal Received Quality (dB). |
CSQ | Signal strength number (0 to 31). |
Examples:
Display the current cellular module status:
gsminfoOutput:
Manufacturer : Quectel
Model : EC25-EUX
Revision : EC25EUXGAR08A05M1G
Firmware Release : EC25EUXGAR08A05M1G_01.001.01.001
IMEI : 86584__________
ICCID : 89420310__________
IMSI : 23003__________
SMS Center : +420__________
Registration : Home Network
Operator : Vodafone CZ
Technology : LTE
PLMN : 23003
Cell : 10A804
TAC : 947C
Channel : 1849
Band : B3
Signal Strength : -90 dBm
Signal Quality : -12 dB
RSSI : -57 dBm
RSRP : -90 dBm
RSRQ : -12 dB
CSQ : 11gsmat
This command sends an AT command to the cellular module.
Synopsis:
gsmat [-t <timeout>] <AT command>Options:
| Option | Description |
|---|---|
-t | The timeout for the response from the cellular module. If not specified, the default value is 10 seconds. |
Examples:
Determine the type and firmware version of the cellular module:
gsmat ATIDetermine the IMEI code of the cellular module:
gsmat AT+GSNgsmat2
💡 This command is not supported by routers of v1 production line.
This command sends an AT command to the second cellular module, if installed in the router.
Synopsis:
gsmat2 [-t <timeout>] <AT command>Options:
| Option | Description |
|---|---|
-t | The timeout for the response from the cellular module. If not specified, the default value is 10 seconds. |
Examples:
Determine the type and firmware version of the second cellular module:
gsmat2 ATIDetermine the IMEI code of the second cellular module:
gsmat2 AT+GSNgsmpwr
💡 This command is not supported by routers of v1 production line.
The gsmpwr utility is used to control the power supply of the primary cellular module.
Synopsis:
gsmpwr on [<sim>] | off | shutdownCommands:
| Command | Description |
|---|---|
on [<sim>] | Turn on the power for the cellular module. You can optionally specify the SIM card slot (1 or 2) to activate a specific SIM upon power-up. |
off | Turn off the power for the cellular module abruptly. |
shutdown | Gracefully shut down the cellular module using an AT command and then turn off its power. Please note that execution may take a few seconds. |
Warning
It is highly recommended to use the gsmpwr shutdown command prior to using the gsmpwr off command to increase the lifetime of the cellular module.
Examples:
Turn on the power for the cellular module and activate SIM card slot 1:
gsmpwr on 1Gracefully shut down the cellular module:
gsmpwr shutdownTurn off the power for the cellular module abruptly:
gsmpwr offgsmpwr2
💡 This command is not supported by routers of v1 production line.
The gsmpwr2 utility is used to control the power supply of the second cellular module, if installed in the router. For usage, see the gsmpwr command.
Synopsis:
gsmpwr2 on [<sim>] | off | shutdownWarning
It is highly recommended to use the gsmpwr2 shutdown command prior to using the gsmpwr2 off command to increase the lifetime of the cellular module.
Examples:
Turn on the second cellular module using the first SIM card:
gsmpwr2 on 1Gracefully shut down the second cellular module:
gsmpwr2 shutdowngsmsms
This program has been deprecated and was removed starting with firmware version 6.6.x. Please use the sms command instead, see Chapter SMS.
hwclock
This command is used to query and set the hardware clock (RTC).
Synopsis:
hwclock [-swul] [--systz] [-f DEV]Options:
| Option | Description |
|---|---|
-s | Set the system time from the hardware clock. |
-w | Set the hardware clock to the current system time. |
--systz | Set the in-kernel timezone and correct the system time if the RTC is kept in local time. |
-f DEV | Use the specified RTC device (e.g., /dev/rtc2). |
-u | Assume the hardware clock is kept in UTC. |
-l | Assume the hardware clock is kept in local time. If neither -u nor -l is specified, the setting is read from /etc/adjtime. |
Examples:
Display the current hardware clock:
hwclockOutput:
Wed Apr 22 08:24:52 2026 0.000000 secondsSet the hardware clock to the current system time (UTC):
hwclock -w -uSet the system time from the hardware clock:
hwclock -sio
This program can be used to read digital inputs and to control digital outputs of the router. If installed, it also supports an expansion ports of the router.
Synopsis:
io [get <pin>] | [set <pin> <value>]Options:
| Option | Description |
|---|---|
get | Get the state of input |
set | Set the state of output |
Examples:
# Get the state of digital input BIN0
io get bin0
# Get the state of analog input AN1 on expansion port XC-CNT
io get an1
# Get the state of counter input CNT1 on expansion port XC-CNT
io get cnt1
# Set the state of digital output OUT0 to 1
io set out0 1led
💡 This command is not supported by routers of v1 production line.
This program can be used to control the USR or PWR LED of the router.
Synopsis:
led [-p] [-u] <command>Options:
| Option | Description |
|---|---|
-p | Control of PWR LED |
-u | Control of USR LED (default) |
Commands:
| Command | Description |
|---|---|
on | Power on the LED |
off | Power off the LED |
slow | Start blinking the LED slowly |
fast | Start blinking the LED fast |
Examples:
# Turn on the USR LED
led on
# Start blinking slowly with the USR LED
led slow
# Control the PWR LED — turn it off
led -p offlpm
💡 This command is not supported by routers of v1, v2, ICR-2000, ICR-2400, ICR-2500, and ICR-2600 production lines.
This program can be used to switch the router into the Low Power Mode. The router can be awoken up by an event according to the specified parameters. The first option is to wake up the router at the time the specified time period has expired and the second option is to wake up the router by activating the digital input. If both parameters were specified, the router will wake up at the time when the first event comes.
Synopsis:
lpm [-b] [-i <interval>]Options:
| Option | Description |
|---|---|
-b | Wake up the router by activating the digital input. For SmartFlex, SmartMotion, ICR-2800, ICR-4200, and ICR-4400 router platforms use input BIN1. For SmartStart and ICR-3200 router platforms use input BIN0. Note: This option is not supported by routers of the ICR-2700 production line. |
-i | Wakes up the router after the specified time interval has elapsed. The interval is defined in seconds, ranging from 1 to 16,777,215. |
Examples:
# Sleep the router for five minutes
lpm -i 300
# Sleep the router and wake up by activating the digital input
lpm -b
# Sleep the router for five minutes or less if the digital input is activated within five minutes
lpm -b -i 300mac
This program can be used to display the MAC address of eth0.
Synopsis:
mac [<separator>]Examples:
# Display the MAC address of eth0 using '-' as the separator instead of the default ':'
mac -port1
This program can be used to control the first expansion port.
Synopsis:
port1 [on|off|auto|rs232|rs485]Options:
| Option | Description |
|---|---|
on | Turn on the first expansion port. |
off | Turn off the first expansion port. |
auto | Turn on the first expansion port and set the flow control (CTS signal) to RS232 or RS485 mode depending on the type of the expansion board. |
rs232 | Turn on the first expansion port and set the flow control (CTS signal) to RS232 mode. |
rs485 | Turn on the first expansion port and set the flow control (CTS signal) to RS485 mode. |
Examples:
Enable the first expansion port in RS485 mode:
port1 rs485Disable the first expansion port:
port1 offport2
This program can be used to control the second expansion port.
Synopsis:
port2 [on|off|auto|rs232|rs485]Options:
| Option | Description |
|---|---|
on | Turn on the second expansion port. |
off | Turn off the second expansion port. |
auto | Turn on the second expansion port and set the flow control (CTS signal) to RS232 or RS485 mode depending on the type of the expansion board. |
rs232 | Turn on the second expansion port and set the flow control (CTS signal) to RS232 mode. |
rs485 | Turn on the second expansion port and set the flow control (CTS signal) to RS485 mode. |
Examples:
Enable the second expansion port in RS232 mode:
port2 rs232Disable the second expansion port:
port2 offportd
This program can be used for transparent transfer of data from the serial line by TCP or UDP.
Synopsis:
portd -c <device> [-b <baudrate>] [-d <databits>] [-p <parity>] [-s <stopbits>] [-l <split timeout>] [-4] [-h <hostname>] [-o <proto>] -t <port> [-k <keepalive time>] [-i <keepalive interval>] [-r <keepalive probes>] [-x] [-z] [-j <inactivity timeout>] [-u <user>] [-n] [-f]Options:
| Option | Description |
|---|---|
-c | Serial line device |
-b | Baudrate |
-d | Number of data bits |
-p | Parity — even, odd or none |
-s | Number of stop bits |
-l | Split timeout |
-4 | Forced detection Expansion port 485 |
-h | Hostname |
-o | Protocol TCP or UDP |
-t | TCP or UDP port |
-k | Keepalive time |
-i | Keepalive interval |
-r | Keepalive probes |
-x | Use signal CD as indicator of the TCP connection |
-z | Use Data Terminal Ready (DTR) signal to control the TCP connection. The program monitors the serial port's CD pin, and if it is de-asserted by the connected device, the TCP connection is terminated. |
-j <timeout> | Sets an inactivity timeout in seconds. If no data is transferred over the network socket for this duration, the connection is closed. A value of 0 disables this feature. |
-n | Rejects new connections in server mode. If a client is already connected, any new incoming connection attempts will be rejected until the current one is closed. |
-u <user> | Specifies a user to drop privileges to after the program has been initialized. |
-f | Enables hardware flow control (RTS/CTS). The RTS pin is asserted when a network connection is active. |
Examples:
Run a TCP server listening on port 1000. After a TCP connection, the program transparently transmits data from the serial port at 115200 bit/s, 8N1:
portd -c /dev/ttyS0 -b 115200 -t 1000 &Connect as a TCP client to a remote server:
portd -c /dev/ttyS0 -b 115200 -h 192.168.1.100 -t 2000 &pse
💡 This program is only supported on models supporting the PoE PSE functionality.
This program can be used to enable/disable the PoE PSE functionality on a router.
Synopsis:
pse [port] [command]Port Options:
| Port | Description |
|---|---|
eth0 | Ethernet ETH0 interface (port). |
eth1 | Ethernet ETH1 interface (port), if equipped on the router. |
lanx | Port of an Ethernet switch interface, if equipped on the router. Replace x with a port number. |
Command Options:
| Command | Description |
|---|---|
on | Enable the PoE PSE on specified interface (port). |
off | Disable the PoE PSE on specified interface (port). |
Examples:
# Enable the PoE PSE on eth1 Ethernet interface
pse eth1 on
# Enable the PoE PSE on lan2 port of Ethernet switch interface
pse lan2 onreboot
This command reboots the router.
Synopsis:
reboot [-d <delay>] [-n] [-f]Options:
| Option | Description |
|---|---|
-d <delay> | Delay interval in seconds before rebooting. |
-n | Do not call sync() before reboot. |
-f | Force reboot without calling shutdown. |
Examples:
Reboot the router immediately:
rebootReboot the router after a 10-second delay:
reboot -d 10report
This command generates and displays the router system report from the command line.
Warning
Sensitive data from the report are filtered out for security reasons.
Synopsis:
report [<options>]Options:
| Option | Description |
|---|---|
| no option | Report all sections except the configuration one. |
-a | Report all sections. |
-s | Report status section. |
-m | Report router apps section. |
-l | Report log section. |
-c | Report configuration section. |
Examples:
Generate a full diagnostic report (all sections except configuration):
reportGenerate only the status section:
report -sGenerate full report including configuration:
report -asms
This command sends an SMS message to a specified phone number.
Synopsis:
sms <phone_number> <text>Arguments:
| Argument | Description |
|---|---|
<phone_number> | The recipient's phone number in international format (e.g., +420123456789). |
<text> | The text of the SMS message. Enclose in quotes if it contains spaces. |
Examples:
Send an SMS message to a specified phone number:
sms +420123456789 "Hello world"status
This command displays the status of the router’s interfaces or system. The output corresponds to the information available in General Status and Mobile WAN Status in the router’s web administration.
Synopsis:
status [-h] [-v] [eth | geoloc | gnss | vlan | mobile | module | mwan | sim | bard | ports | security | sys | hw | wifi ap | wifi sta]Options:
| Option | Description |
|---|---|
-h | Generate HTML output (used when called by the web interface). |
-v | Verbose mode; displays more detailed information. Data amounts are reported in bytes rather than dynamic units (KB, MB, etc.). |
eth | Displays the status of Ethernet interfaces (e.g., eth0, eth1), including link state, speed, and data statistics. |
geoloc | Displays the router's last known geographical coordinates (latitude and longitude), determined by the GNSS receiver. |
gnss | Shows the current status of the GNSS receiver, including the UTC time, fix type (e.g., 2D, 3D), dilution of precision (HDOP), and the number of satellites in use versus in view. |
vlan | Lists the status of configured Virtual LAN (VLAN) interfaces, including their names, associated physical interfaces, and VLAN IDs. |
mobile | Shows the status of the mobile radio connection, including registration status, operator, network technology (e.g., LTE, 5G), and signal quality metrics. |
module | Displays the status of the cellular module(s), which can be module 1, module 2, etc., if available. |
mwan | Provides the status of the Mobile WAN network interface, including IP address, DNS servers, and connection uptime. |
sim 1 | Displays daily statistics for SIM card 1, including data usage (RX/TX), connection count, signal history, cell changes, and network availability. |
sim 2 | Displays daily statistics for SIM card 2 (if available). |
sim 1 full / sim 2 full | Displays a full report for the specified SIM card, covering Today, Yesterday, This Week, Last Week, This Period, and Last Period. |
bard | Displays the status of the Backup and Recovery Daemon (BARD), indicating whether it is active and monitoring backup routes. |
ports | Shows the status of available peripheral ports (e.g., serial ports, USB). |
security | Shows recent user login activity, including the last successful login, the count of failed login attempts, and the source IP address for each event. |
sys | Provides general system information, such as uptime, memory usage, and supply voltage. |
hw | Displays hardware capabilities and interfaces, including the presence of wireless modules (Mobile WAN, GNSS, Wi-Fi, Bluetooth), physical ports (Serial, I/O, PoE), and the product's designated region. |
wifi ap | Displays the status of the WiFi Access Point. |
wifi sta | Displays the status of the WiFi Station (client) connection. |
Examples:
Show verbose status of the mobile connection:
status -v mobileExample output:
Registration : Home Network
Operator : Vodafone CZ
Technology : LTE
PLMN : 23003
Cell : 10A804
TAC : 947C
Channel : 1849
Band : B3
Signal Strength : -90 dBm
Signal Quality : -7 dB
RSSI : -63 dBm
RSRP : -90 dBm
RSRQ : -7 dB
SINR : 18 dB
CSQ : 11Show system information:
status sysShow hardware feature information:
status hwstty
This program can be used to print or to change terminal characteristics.
Synopsis:stty [-a|g] [-F DEVICE] [SETTING]...
Options:
| Option | Description |
|---|---|
-F DEVICE | Open device instead of stdin |
-a | Print all current settings in human-readable form |
-g | Print in stty-readable form |
[SETTING] | See manpage |
Examples:
To get current parameters of the first UART serial port.stty -F /dev/ttyS0
To only get actual speed of the second UART serial port.stty -F /dev/ttyS1 speed
To set parameters of the first UART serial port to:
- speed to 1200 bps
- character size to 7 bits
- 2 stop bits
- disable software output flow control
- reset parameters to system default raw mode
stty -F /dev/ttyS0 1200 cs7 cstopb -ixon rawtpm2
💡 TPM features are available only on products that are equipped with a TPM module. TPM support can be verified either in the Hardware Manual or directly in the router console, as described below.
This program can be used to work with the TPM 2.0 (Trusted Platform Module) chip mounted directly onto the router’s mainboard.
Note: To verify that TPM functionality is supported on your device, use one of the following procedures:
- In router console, execute the command:
ls /dev/tpm0- If you get "No such file or directory" response, the TPM chip is not available.
- If you get "/dev/tpm0" response, the TPM chip is available.
- In router console, execute TPM command to display fixed TPM properties:
tpm2 getcap properties-fixed- If several error messages are displayed, the TPM chip is not available.
- If you get a list of TPM properties, the TPM chip is available.
Synopsis:tpm2 <subcommand> [<options>...]
The table below lists the most important tpm2 subcommands. For more details about the subcommands, see tpm2-tools documentation.
tpm2 subcommands:
| Subcommand | Description |
|---|---|
getcap | Display TPM capabilities in a human-readable form. |
create | Create a child object. |
createek | Generate TCG profile compliant endorsement key. |
createak | Generate attestation key with given algorithm under the endorsement hierarchy. |
createprimary | Create a primary key. |
load | Load an object into the TPM. |
loadexternal | Load an external object into the TPM. |
readpublic | Read the public area of a loaded object. |
evictcontrol | Make a transient object persistent or evict a persistent object. |
clear | Clear lockout, endorsement, and owner hierarchy authorization values. |
getrandom | Retrieve random bytes from the TPM. |
hash | Perform a hash operation with the TPM. |
hmac | Perform an HMAC operation with the TPM. |
sign | Sign a hash or message using the TPM. |
verifysignature | Validate a signature using the TPM. |
encryptdecrypt | Perform symmetric encryption or decryption. |
ecdhzgen | Recover the shared secret value (Z) from a public point and a specified private key. |
nvdefine | Define a TPM Non-Volatile (NV) index. |
nvundefine | Delete a Non-Volatile (NV) index. |
nvread | Read the data stored in a Non-Volatile (NV) index. |
nvwrite | Write data to a Non-Volatile (NV) index. |
xbus
This program is primarily used for internal process communication. It can be used as a watchdog of a user process.
Synopsis:xbus [command]
xbus commands:
| Command | Description |
|---|---|
subscribe <topic> [<script>] | Subscribe to a particular topic. |
publish <topic> <payload> | Publish the payload for the topic¹. |
write <topic> <payload> | Publish and store the payload for the topic¹. |
read <topic> | Read stored payload of the topic. |
list | List all the stored topics. |
¹ Do not execute this command more than once per second.
Examples:
Set the watchdog for process "user_process" to 10 seconds. If this command is not re-executed within 10 seconds, the router will reboot.xbus write watchdog/proc/user_process "Timeout:10"
Suspend the watchdog for process "user_process".xbus write watchdog/proc/user_process "Timeout:0"
File/Directory Management Commands
Essential for navigating and manipulating the filesystem, these commands allow users to create, list, modify, and remove files and directories, making them indispensable for day-to-day operations on a Unix-like system.
basename
This command can be used to strip directory path and .SUFFIX from FILE.
Synopsis:basename FILE [SUFFIX]
Examples:
Strip directory from /home/myfile.txt path, including .txt extension.
basename /home/myfile.txt .txt
myfilecat
This command concatenates files and prints on the standard output.
Synopsis:cat [-u] [<file>] ...
Options:
| Option | Description |
|---|---|
-u | Ignored since unbuffered I/O is always used. |
Examples:
View the contents of file /proc/tty/driver/atmel_serial (serial port information on v2i routers).cat /proc/tty/driver/atmel_serial
Copy the contents of the router configuration files in /tmp/my.cfg.cat /etc/settings.* > /tmp/my.cfg
cd
This command can be used to change the current working directory.
Synopsis:cd [-P] [-L] [<directory>]
Options:
| Option | Description |
|---|---|
-P | Do not follow symbolic links |
-L | Follow symbolic links (default) |
Examples:
Move to home directory (/root).cd
Move to directory /mnt.cd /mnt
chdir
The chdir command, also known as cd in many shell environments, is utilized to change the current working directory of the shell session.
cmp
The cmp utility compares two files of any type and writes the results to the standard output.
Synopsis:cmp [-l] [-s] <file1> <file2> [<skip1> [<skip2>]]
Options:
| Option | Description |
|---|---|
-l | Print the byte number (decimal) and the differing byte values (octal) for each difference. |
-s | Print nothing for differing files; return exit status only. |
By default, cmp is silent if the files are the same; if they differ, the byte and line number at which the first difference occurred is reported. Bytes and lines are numbered beginning with one. If <file2> is not specified, standard input is used instead.
The optional arguments <skip1> and <skip2> are the byte offsets from the beginning of <file1> and <file2> respectively, where the comparison will begin. The offset is decimal by default, but may be expressed as a hexadecimal or octal value.
Examples
Compare two files and report the first difference:
cmp file1.txt file2.txtCheck silently whether two files are identical:
cmp -s file1.bin file2.bin && echo "identical" || echo "differ"cp
This command can be used to copy files and directories.
Synopsis:cp [<option>] <source> <dest>
Options:
| Option | Description |
|---|---|
-a | Preserve all attributes. |
-R, -r | Copy directories recursively. |
-d, -P | Never follow symbolic links. |
-H, -L | Follow command-line symbolic links. |
-p | Preserve the mode, ownership, and timestamps attributes. |
-f | If an existing destination file cannot be opened, remove it and try again. |
-i | Prompt before overwrite. |
-n | Don't overwrite. |
-l, -s | Create (sym)links |
-T | Refuse to copy if DEST is a directory |
-t DIR | Copy all SOURCEs into DIR |
-u | Copy only newer files |
Examples:
Copy the system log to directory /mnt.cp /var/log/messages* /mnt
Copy configuration profile "Alternative 1" to profile "Standard".cp -r /etc/alt1/* /etc
cut
This command prints selected fields from each input FILE to standard output.
Synopsis:cut [OPTIONS] [FILE]...
Options:
| Option | Description |
|---|---|
-b LIST | Output only bytes from LIST |
-c LIST | Output only characters from LIST |
-d CHAR | Field delimiter for input (default -f TAB, -F run of whitespace) |
-O CHAR | Field delimiter for output (default = -d for -f, one space for -F) |
-D | Don't sort/collate sections or match -fF lines without delimiter |
-f LIST | Print only these fields (-d is single char) |
-s | Output only the lines containing delimiter |
-n | Ignored |
Examples:
Display the 1st field of each line, using tab as the field separator.cut -f1 file.txt
Displays the 2nd field of each line, using colon as the field separator.
echo a:b | cut -d: -f2
bDisplay the 2nd and every later field.
echo a b c d | cut -d" " -f2-
b c dInstead of fields, treats characters. Display the third and fourth character.
echo abcd | cut -c3,4
cddd
This command can be used to copy a file and convert the data format in the process, according to the operands specified.
Synopsis:dd [if=FILE] [of=FILE] [bs=N] [count=N] [skip=N] [seek=N]
Options:
| Option | Description |
|---|---|
if=FILE | Read from FILE instead of stdin |
of=FILE | Write to FILE instead of stdout |
bs=N | Read and write N bytes at a time |
count=N | Copy only N input blocks |
skip=N | Skip N input blocks |
seek=N | Skip N output blocks |
N | May be suffixed by c (1), w (2), b (512), kB (1000), k (1024), MB, M, GB, G |
Examples:
Erase the microSD card, which is available as /dev/sda.dd if=/dev/zero of=/dev/sda bs=4k
Create a backup image of a device:
dd if=/dev/sda of=/mnt/backup.img bs=1Mdecode
This command is designed for decoding Base64-encoded values, making it an essential tool for working with configuration files or other data that utilize Base64 encoding for obfuscation or storage efficiency. The decoded value is printed to the standard output, allowing for direct observation or redirection to a file for further use.
Synopsis:decode <base64>
Description:
The decode command takes a single argument, a Base64-encoded string, and prints its decoded value. This functionality is particularly useful in scenarios where configuration files or data are encoded to prevent manipulation or ensure compatibility.
Options:
This proprietary command is straightforward and does not require additional options for its operation.
Examples:
Decode a Base64-encoded string.
decode SGVsbG8sIFdvcmxkIQ==This example will output the decoded string of the provided Base64-encoded value, in this case, "Hello, World!".
dirname
This command strips non-directory suffix from FILENAME.
Synopsis:dirname FILENAME
Examples:
Strip non-directory suffix from /home/MyFolder/myfile.txt path.
dirname /home/MyFolder/myfile.txt
/home/MyFolderfind
Command to search for files in a directory hierarchy.
Synopsis:find [<path> ...] [<expression>]
Options:
The default path is the current directory, default expression is '-print'. Type find --help for help or look up online man page for more detailed description. Expression may consist of:
| Option | Description |
|---|---|
-follow | Dereference symbolic links |
-name <pattern> | File name (leading directories removed) matches <pattern> |
-print | Print (default and assumed) |
-type X | Filetype matches X (where X is one of: f,d,l,b,c,...) |
-perm <perms> | Permissions match any of (+NNN); all of (-NNN); or exactly (NNN) |
-mtime <days> | Modified time is greater than (+N); less than (-N); or exactly (N) days |
-mmin <mins> | Modified time is greater than (+N); less than (-N); or exactly (N) minutes |
-exec <cmd> | Execute command with all instances of {} replaced by the files matching <expression> |
Examples:
Search for files in your home directory which have been modified in the last twenty-four hours.find $HOME -mtime 0
Search for files which have read and write permission for their owner, and group, but which other users can read but not write to.find . -perm 664
grep
This program searches the named input FILEs (or standard input if no files are named, or the file name - is given) for lines containing a match to the given PATTERN. By default, grep prints the matching lines.
Synopsis
grep [<options> ...] <pattern> [<file> ...]Options
| Option | Description |
|---|---|
-H | Print the filename for each match |
-h | Suppress the prefixing of filenames on output when multiple files are searched |
-n | Prefix each line of output with the line number within its input file |
-l | Suppress normal output; instead print the name of each input file from which output would normally have been printed |
-L | Suppress normal output; instead print the name of each input file from which no output would normally have been printed |
-c | Suppress normal output; instead print a count of matching lines for each input file |
-o | Show only the matching part of the line |
-q | Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. |
-v | Invert the sense of matching, to select non-matching lines |
-s | Suppress error messages about nonexistent or unreadable files |
-r | Recurse |
-R | Recurse and dereference symlinks |
-i | Ignore case distinctions |
-w | Match whole words only |
-x | Match whole lines only |
-F | Interpret PATTERN as a list of fixed strings, separated by new lines, any of which is to be matched |
-E | PATTERN is an extended regexp |
-A N | Print N lines of trailing context after each match |
-B N | Print N lines of leading context before each match |
-C N | Print N lines of context before and after each match (same as -A N -B N) |
-m N | Match up to N times per file |
-e PTRN | Use PATTERN as the pattern; useful to protect patterns beginning with - |
-f FILE | Obtain patterns from FILE, one per line |
Examples
See all lines of the system log in which the word "error" occurs.
grep error /var/log/messagesView all processes whose name contains the string "ppp".
ps | grep pppFind the word error and print 2 lines of context before and after each match:
grep -C 2 "error" /var/log/messagesgunzip
This program can be used to decompress FILE (or standard input if the filename is -).
Synopsis
gunzip [-c] [-f] [-t] <filename>Options
| Option | Description |
|---|---|
-c | Write output to standard output |
-f | Force decompression even if the file has multiple links or the corresponding file already exists, or if the compressed data is read from or written to a terminal |
-t | Test. Check the compressed file integrity |
Examples
Decompress the file test.tar.gz (creates file test.tar).
gunzip test.tar.gzDecompress and write output to standard output:
gunzip -c test.tar.gz | tar -xf -gzip
This program can be used to compress FILE with maximum compression.
Synopsis
gzip [-c] [-d] [-f] <filename>Options
| Option | Description |
|---|---|
-c | Write output to standard output |
-d | Decompress |
-f | Force compression even if the file has multiple links or the corresponding file already exists, or if the compressed data is read from or written to a terminal |
Examples
Compress the file test.tar (creates file test.tar.gz).
gzip test.tarDecompress a file using gzip:
gzip -d test.tar.gzhead
This program prints the first 10 lines of each file to standard output. With more than one file, precede each with a header giving the file name. With no file, or when the file is a dash (-), read standard input.
Synopsis
head [<option(s)>] [<file(s)>]Options
| Option | Description |
|---|---|
-n NUM | Print the first NUM lines instead of the first 10 |
-c NUM | Output the first NUM bytes |
-q | Never output headers giving file names |
-v | Always output headers giving file names |
Examples
Display the first 5 lines of the system log:
head -n 5 /var/log/messagesDisplay the first 100 bytes:
head -c 100 /var/log/messagesjq
💡 This command is not supported by routers of v1 and v2 production lines.
This command is a powerful tool for processing JSON inputs, applying filters to JSON text, and producing the output as JSON. It can manipulate, filter, and transform structured data with its directive.
Synopsis
jq [options] <jq filter> [file...]
jq [options] --args <jq filter> [strings...]
jq [options] --jsonargs <jq filter> [JSON_TEXTS...]Options
| Option | Description |
|---|---|
-r | Output raw strings, not JSON texts |
-c | Produce compact output instead of pretty-printed output |
-f | Load a jq program from a file |
--arg name value | Pass argument to the filter |
Examples
Output the JSON object unmodified, with formatting.
echo '{"foo": 0}' | jq .Extract the value of the key bar from the JSON input.
echo '{"foo": 0, "bar": 1}' | jq '.bar'Apply the filter to each element in the JSON array, outputting the value of the foo key.
echo '[{"foo": 0}, {"foo": 1}]' | jq '.[] | .foo'Add a new key-value pair to the JSON object read from data.json.
cat data.json | jq --arg keyName "myKey" --arg keyValue "myValue" '. + {$keyName: $keyValue}'less
This command is a terminal pager program that displays the contents of a text file one screen at a time. Unlike most pager programs, less allows backward movement in the file as well as forward movement.
Synopsis
less [options] file ...Options
For a complete list of options, refer to the less(1) — Linux manual page.
Some commonly used options include:
-N: Displays line numbers at the beginning of each line.-i: Ignores the case when searching.-F: Exits if the content can be displayed on one screen.-R: Displays ANSI color escape sequences in raw form.
Examples
Display the contents of file.txt, allowing navigation through the file.
less file.txtDisplay file.txt with line numbers.
less -N file.txtSearch for search_term in file.txt and pipe the output to less, allowing the user to view the search results with ANSI color formatting.
grep 'search_term' file.txt | less -ROpen log.txt in less, automatically following the end of the file as new lines are added, similar to tail -f.
less +F log.txtln
This program can be used to make links between files.
Synopsis
ln [ option ] < target > ... < link_name > | < directory >Options
| Option | Description |
|---|---|
-s | Make symbolic links instead of hard links |
-f | Remove existing destination files |
-n | No dereference symlinks — treat like a normal file |
-b | Make a backup of the target (if exists) before the link operation |
-S | Use suffix instead of ~ when making backup files |
Examples
Create a symbolic link to the file /var/log/messages called my.log.
ln -s /var/log/messages my.logCreate a hard link:
ln /var/log/messages /tmp/messages.lnkls
This program can be used to list directory contents.
Synopsis
ls [ option ] < filename > ...Options
| Option | Description |
|---|---|
-1 | List files in a single column |
-A | Do not list implied . and .. |
-a | Do not hide entries starting with . |
-C | List entries by columns |
-c | With -l: show ctime |
-d | List directory entries instead of contents |
-e | List both full date and full time |
-i | List the i-node for each file |
-l | Use a long listing form |
-n | List numeric UIDs and GIDs instead of names |
-L | List entries pointed to by symbolic links |
-r | Sort the listing in reverse order |
-S | Sort the listing by file size |
-s | List the size of each file, in blocks |
-t | With -l: show modification time |
-u | With -l: show access time |
-v | Sort the listing by version |
-x | List entries by lines instead of by columns |
-X | Sort the listing by extension |
Examples
View detailed content of the directory /mnt.
ls -l /mntList all files including hidden ones in the current directory:
ls -amkdir
This program is used to make directories.
Synopsis
mkdir [<option>] directory ...Options
| Option | Description |
|---|---|
-m | Set permission mode (as in chmod), not rwxrwxrwx — umask |
-p | No error if existing, make parent directories as needed |
Examples
Create the directory /tmp/test/example.
mkdir -p /tmp/test/examplemv
This program can be used to move or rename files.
Synopsis
mv [-f] [-fin] <source> ... <dest>Options
| Option | Description |
|---|---|
-f | Don't prompt before overwriting |
-i | Interactive, prompt before overwrite |
-n | Don't overwrite an existing file |
-T | Refuse to move if DEST is a directory |
-t DIR | Move all SOURCEs into DIR |
Examples
Rename the file abc.txt to def.txt.
mv abc.txt def.txtMove all files with the extension .txt to the directory /mnt.
mv *.txt /mntpwd
This program can be used to print the path of the current directory.
Synopsis
pwdExamples
Print the path of the current directory, which is /home/httpd in this case.
pwd
/home/httpdStore the current directory path in a variable:
DIR=$(pwd)
echo "Working in: $DIR"Output:
Working in: /home/httpdreadlink
This command displays the value of a symlink stored in a link file. If given a non-symlink, it produces no output.
Synopsis
readlink FILEExamples
Display the symlink target of the report command.
readlink /usr/bin/report
/usr/bin/aboxrealpath
This command returns the absolute pathname of a given file name.
Synopsis
realpath FILEExamples
Return the absolute pathname of myfile.txt located at the current directory, here in /home/MyFolder/.
realpath myfile.txt
/home/MyFolder/myfile.txtrm
This program can be used to remove files or directories.
Synopsis
rm [-i] [-f] [-r] <file> ...Options
| Option | Description |
|---|---|
-i | Always prompt before removing each destination |
-f | Remove existing destinations, never prompt |
-r | Remove the contents of directories recursively |
Examples
Remove all files with the extension .txt in the current directory.
rm *.txtRemove the directory /tmp/test and all subdirectories.
rm -rf /tmp/testrmdir
This program can be used to remove empty directories.
Synopsis
rmdir [-p] [--ignore-fail-on-non-empty] <filename>Options
| Option | Description |
|---|---|
-p | Remove directory and its ancestors; e.g., rmdir -p a/b/c is similar to rmdir a/b/c a/b a. |
--ignore-fail-on-non-empty | Ignore each failure that is solely because a directory is non-empty. |
Examples
Remove the empty directory /tmp/test.
rmdir /tmp/testRemove directory /tmp/test and its parent /tmp if both are empty:
rmdir -p /tmp/testsed
This program can be used for filtering and transforming text.
Synopsis
sed [ -e ] [ -f ] [ -i ] [ -n ] [ -r ] pattern [ -files ]Options
| Option | Description |
|---|---|
-e | Add the script to the commands to be executed |
-f | Add script-file contents to the commands to be executed |
-i | Edit files in place (makes backup if extension supplied) |
-n | Suppress automatic printing of pattern space |
-r | Use extended regular expression syntax |
If no -e or -f is given, the first non-option argument is taken as the sed script to interpret. All remaining arguments are names of input files; if no input files are specified, then the standard input is read. Source files will not be modified unless the -i option is given.
Examples
Change the parameter PPP_APN in the file /etc/settings.ppp to the value "internet".
sed -e "s/\(PPP_APN=\).*/\1internet/" -i /etc/settings.pppDelete all blank lines from a file:
sed '/^$/d' file.txtshred
This program can be used to delete a file completely from non-volatile memory. This command overwrites the contents of a file multiple times, using patterns chosen to maximize the destruction of the residual data, making it harder for even very expensive hardware probing to recover it.
Synopsis
shred [OPTIONS] [FILE]Options
| Option | Description |
|---|---|
-f | Change permissions to allow writing if necessary |
-n N | Overwrite N times instead of the default (default is 3 times) |
-z | Add a final overwrite with zeros to hide shredding |
-u | Truncate and remove file after overwriting |
Examples
Overwrite the data of file1.txt and file2.txt using the default shredding methods.
shred file1.txt file2.txtOverwrite the data of file1.txt using the default shredding methods and delete the file.
shred -u file1.txtOverwrite the data of file1.txt 10 times.
shred -n 10 file1.txtsplit
This program splits a single file (INPUT) into multiple files. A custom PREFIX for the name of the output files can be specified.
Synopsis
split [OPTIONS] [INPUT [PREFIX]]Options
| Option | Description |
|---|---|
| `-b N[k | m]` |
-l N | Split input file by N lines (by default 1000 lines) |
-a N | Use N letters as suffix for the name of the output files (by default 2 letters) |
Examples
Split the file file.img into files (xaa, xab, xac, ...) with a size of 50 kB each.
split -b 50k file.imgSplit the file file.txt into files (file_a, file_b, file_c, ...) each containing 200 lines.
split -l 200 -a 1 file.txt file_sync
This command forces an immediate transfer of buffered data blocks in memory or in FILEs to the disk.
Synopsis
sync [OPTIONS] [FILEs]...Options
| Option | Description |
|---|---|
-d | Avoid syncing metadata |
-f | Sync filesystems underlying FILEs |
Examples
Flush all pending writes to disk:
syncSync only the data of a specific file:
sync -d /var/log/messagestail
This program can be used to output the last part of files.
Synopsis
tail [ -n <number>] [ -f ]Options
| Option | Description |
|---|---|
-n | Print the last N lines instead of the last 10 |
-f | Output data as the file grows |
Examples
Show the last 30 lines of /var/log/messages.
tail -n 30 /var/log/messagesFollow the system log in real time:
tail -f /var/log/messagestar
This program can be used to create, extract or list files from a tar file.
Synopsis:tar -[czxtv0] [ -f tarfile ] [ -C dir ] [ file ] ...
Options:
| Option | Description |
|---|---|
c | Create |
x | Extract |
t | List |
-f FILE | Name of TARFILE or "-" for stdin |
-C DIR | Change to directory DIR before operation |
-v | Verbosely list files processed |
-O | Extract to stdout |
-o | Don't restore user:group |
-k | Don't replace existing files |
-z | (De)compress using gzip |
-a | (De)compress based on extension |
-h | Follow symlinks |
Examples:
Creating log.tar archive that contains files from the directory /var/log.
tar -cf log.tar /var/logExtract files from the archive log.tar.
tar -xf log.tarCreate a compressed archive using gzip:
tar -czf log.tar.gz /var/logtouch
This program can be used to update timestamp of file.
Synopsis:touch [-c] <file> [<file> ...]
Options:
| Option | Description |
|---|---|
-c | Do not create any files |
-h | Do not follow links |
Examples:
Create a file, respectively update timestamp of file /tmp/test.
touch /tmp/testUpdate timestamps of multiple files at once:
touch file1.txt file2.txt file3.txtvi
This program can be used to edit and read text file.
Synopsis:vi [-R] [<file> ...]
Options:
| Option | Description |
|---|---|
-R | Read only, do not write to the file |
Examples:
Open file /etc/rc.local in the text editor vi.
vi /etc/rc.localOpen a file in read-only mode:
vi -R /etc/settings.pppwc
Print newline, word, and byte counts for each file, and a total line if more than one file is specified. With no file, or when file is a dash ("-"), read standard input.
Synopsis:wc [<option(s)>] [<file(s)>]
Options:
| Option | Description |
|---|---|
-c | Print the byte counts. |
-l | Print the newline counts. |
-L | Print the length of the longest line. |
-w | Print the word counts. |
Examples:
Count the number of lines in the system log:
wc -l /var/log/messagesCount the number of words:
wc -w file.txtxxd
This is a program is a command-line utility that creates a hex dump of a given file or standard input. It can also convert a hex dump back to its original binary form. This tool is commonly used for debugging, examining binary files, and performing binary file analysis.
Synopsis:xxd [-pri] [-g N] [-c N] [-l LEN] [-s OFS] [-o OFS] [FILE]
Options:
| Option | Description |
|---|---|
-g N | Bytes per group |
-c N | Bytes per line |
-p | Show only hex bytes, assumes -c30 |
-i | C include file style |
-l LENGTH | Show only first LENGTH bytes |
-s OFFSET | Skip OFFSET bytes |
-o OFFSET | Add OFFSET to displayed offset |
-r | Reverse (with -p, assumes no offsets in input) |
Examples:
xxd file.txt
This command generates a hex dump of file.txt, displaying both the hexadecimal values and their corresponding ASCII characters. It's commonly used for inspecting the contents of a file, especially in debugging or when dealing with binary data.
xxd -p file.bin > file.hex
In this scenario, the -p option is used to create a plain hex dump of a binary file (file.bin). The output is redirected to a new file (file.hex). This format is easier to read and manipulate, particularly useful in scenarios involving binary data analysis or modification.
xxd -r file.hex > file.bin
This example shows how to reverse the process: converting a hex dump (file.hex) back into its original binary form (file.bin). The -r option is used for this reverse operation. It's particularly useful when you've made changes to the hex representation of a file and need to revert it to its binary format.
zcat
This command is a utility in Unix-like operating systems that allows users to view the contents of gzip-compressed files directly, without the need to explicitly decompress them first. It is equivalent to running the gunzip -c command and is useful for quickly inspecting the contents of compressed files or for piping the output of compressed files into other commands or programs for further processing.
Synopsis:zcat [options] [file ...]
Description:
Zcat concatenates the uncompressed contents of compressed files to standard output. When no files are specified, or when the file name - is used, zcat reads from standard input. Zcat will decompress all specified files in order, making it convenient for viewing multiple compressed files.
Options:
-h, --help: Display a help message and exit.-V, --version: Display version information and exit.- Additional options available in zcat are generally passed to the gzip command, as zcat is often a symlink to gzip.
Examples:
View the contents of a compressed file:
zcat file.gzConcatenate multiple compressed files:
zcat file1.gz file2.gz file3.gzPipe the contents of a compressed file into grep:
zcat file.gz | grep 'search_pattern'The zcat command's ability to directly read compressed files makes it an invaluable tool for quickly accessing or processing data within gzip-compressed files without the overhead of decompression.
System Commands
System administration commands provide the necessary tools for managing users, system services, and hardware settings. They are crucial for maintaining the system's integrity, security, and performance.
adduser
Warning
Incorrect usage of this command may lead to system malfunction.
The adduser command is used to create a new user or add an existing user to a specified group.
Synopsis:
adduser [OPTIONS] USER [GROUP]Options:
| Option | Description |
|---|---|
-s SHELL | Specify the login shell for the new user. |
-G GRP | Add the user to the specified group. |
| Undocumented options | Undocumented options are not recommended for use if you are not sure what you are doing, as their incorrect usage may lead to system malfunction. |
Examples:
Create a new user john with user role:
adduser -s /bin/false -G users johnCreate a new user george with admin role:
adduser -s /bin/sh -G root georgebackup
This command backs up the router configuration. The configuration is written to standard output and must be redirected to a file using the > operator (the filename is not a command argument). The stored configuration can be restored using the restore command, see Chapter restore.
Synopsis:
backup [<options>] > <filename>Options:
| Option | Description |
|---|---|
-c | Back up the configuration excluding user account data (default if no option is specified). |
-u | Backup user account data only. |
-a | Back up the complete configuration, including user accounts, scripts, and Router Apps settings. |
-f | Filter sensitive information — passwords are replaced by ###REMOVED###. |
-p <password> | Encrypt the backup using AES-256. The output is Base64-encoded. |
Tips
The output filename is specified using shell redirection (>), not as a command argument.
Examples:
Back up the entire configuration to a file:
backup -a > /tmp/my.cfgBack up the entire configuration, filtering out sensitive information:
backup -a -f > /tmp/support-safe.cfgBack up the entire configuration with AES-256 encryption:
backup -a -p MySecretPass > /tmp/backup.encBack up user account data only:
backup -u > /tmp/users.cfgBack up only the configuration:
backup -c > /tmp/config-only.cfgView the backup directly on the console:
backup -cchmod
This command can be used to change file mode bits.
Synopsis:
chmod [-R] <mode> <filename>Options:
| Option | Description |
|---|---|
-R | Change files and directories recursively. |
Examples:
Set rights (permit execution) of script /tmp/script:
chmod 755 /tmp/scriptAllow full access for owner, read-only for others:
chmod 744 /tmp/config.cfgChange permissions recursively:
chmod -R 755 /opt/customchown
This command changes the user and/or group ownership of specified files or directories. This command is crucial for managing permissions and access control in Unix-like operating systems.
Synopsis:
chown [-R] <user>[:<group>] <filename>Options:
| Option | Description |
|---|---|
-R | Change files and directories recursively. |
Examples:
Change owner to root:
chown root /tmp/config.cfgChange owner and group recursively:
chown -R admin:admin /opt/customChange only the group:
chown :network /tmp/log.txtchpasswd
This utility can be used to update user passwords, particularly for bulk updates of multiple users' passwords and for updating without user interaction, such as in scripts.
Synopsis:
chpasswd [options]Options:
| Option | Description |
|---|---|
-c, --crypt-method METHOD | Specify the crypt method (one of NONE, DES, MD5, SHA256, SHA512, BCRYPT, YESCRYPT). |
-e, --encrypted | Supplied passwords are encrypted. |
-h, --help | Display this help message and exit. |
-m, --md5 | Encrypt the clear text password using the MD5 algorithm. |
-R, --root CHROOT_DIR | Directory to chroot into. |
-P, --prefix PREFIX_DIR | Directory prefix. |
-s, --sha-rounds | Number of rounds for the SHA, BCRYPT, or YESCRYPT crypt algorithms. |
Examples:
Update the password for a user, encrypting the password with MD5:
chpasswd -m <<EOF
username:newpassword
EOFUpdate the password for a user, providing an already encrypted password:
chpasswd -e <<EOF
username:encryptedpassword
EOFUpdate the password for two users, specifying the crypt method to SHA512:
chpasswd -c SHA512 <<EOF
username:newpassword
username2:newpassword
EOFclog
This command can be used to print the connection logs.
date
This command can be used to display the current time in the given FORMAT, or set the system date (and time).
Synopsis:
date [-R] [-d <string>] [-s] [-r <file>] [-u] [MMDDhhmm[[CC]YY][.ss]]Options:
| Option | Description |
|---|---|
-R | Output date and time in RFC 2822 format. |
-d <string> | Display time described by STRING, not 'now'. |
-s | Set time described by STRING. |
-r <file> | Display the last modification time of FILE. |
-u | Print or set Coordinated Universal Time. |
Examples:
Display the current date and time:
dateSetting the date and time on December 24, 2011 20:00:
date 122420002011deluser
Warning
Incorrect usage of this command may lead to system malfunction.
The deluser command is used to delete a user from the system.
Synopsis:
deluser [--remove-home] USERDescription:
The deluser command removes the specified user from the system. If the --remove-home option is used, the user's home directory and mail spool will also be deleted.
Options:
| Option | Description |
|---|---|
--remove-home | Remove the user's home directory and mail spool along with the user account. |
Examples:
Delete a user named testuser from the system:
deluser testuserDelete a user named testuser and remove their home directory and mail spool:
deluser --remove-home testuserdf
This command can be used to view report file system disk space usage.
Synopsis:
df [-PkT] [-t TYPE] [FILESYSTEM]...Options:
| Option | Description |
|---|---|
-P | POSIX output format. |
-k | Print sizes in kilobytes. |
-T | Print filesystem type. |
-t TYPE | Print only mounts of this type. |
dmesg
This command can be used to display the Kernel log messages.
Synopsis:
dmesg [-R] [-T] [-c]Options:
| Option | Description |
|---|---|
-R | Display relative time since the router booted in sec.nanosec format. |
-T | Display human-readable timestamp in YYYY-MM-DD hh:mm:ss format. |
-c | Read and clear all messages. |
Examples:
Display latest Kernel log messages and subsequent deletion of the Kernel ring buffer:
dmesg -cDisplay latest Kernel log messages including the human-readable timestamp:
dmesg -Tdoas
This command can be used to execute commands as another user. The command argument is mandatory unless -C, -L, or -s is specified. The user will be required to authenticate by entering their password, unless configured otherwise.
By default, a new environment is created. The variables HOME, LOGNAME, PATH, SHELL, and USER and the umask are set to values appropriate for the target user. DOAS_USER is set to the name of the user executing doas. The variables DISPLAY and TERM are inherited from the current environment. This behavior may be modified by the config file. The working directory is not changed.
Synopsis:
doas [-Lns] [-C config] [-u user] command [args]Options:
| Option | Description |
|---|---|
-L | Clear any persisted authentications from previous invocations, then immediately exit. No command is executed. |
-n | Non-interactive mode, fail if the matching rule doesn't have the nopass option. |
-s | Execute the shell from SHELL or /etc/passwd. |
-C config | Parse and check the configuration file config, then exit. If command is supplied, doas will also perform command matching. In the latter case either ‘permit’, ‘permit nopass’ or ‘deny’ will be printed on standard output, depending on command matching results. No command is executed. |
-u user | Execute the command as user. The default is root. |
Exit Status:
The doas utility exits 0 on success, and > 0 if an error occurs. It may fail for one of the following reasons:
- The config file
/etc/doas.confcould not be parsed. - The user attempted to run a command which is not permitted.
- The password was incorrect.
- The specified command was not found or is not executable.
faillock
💡 This command is not supported by routers of v1 production line.
This program is used to handle user login failures. It allows listing failures for each user, resetting failures, or eventually resetting locked users. Note that this feature is associated with account locking after exceeding the allowed number of unsuccessful login attempts and is not related to the administrative account locking function in the GUI.
Synopsis:
faillock [--user username] [--reset] [--legacy-output]Options:
| Option | Description |
|---|---|
--user username | Apply the command to the specified user. |
--reset | Reset the failure records. This can be used to manually unlock accounts or reset the failure count. |
--legacy-output | Display output in the legacy format. |
Examples:
View the authentication failure records for all users:
faillockView the authentication failure records for the user john:
faillock --user johnView the authentication failure records using the legacy output format:
faillock --legacy-outputReset the failure records for the user john:
faillock --user john --resetfree
This command displays information about free and used memory, reported in kB (kilobytes).
Synopsis:
freeOptions:
This command does not support any options.
Example:
~ # free
total used free shared buff/cache available
Mem: 1008588 141496 834472 188 32620 854040
Swap: 0 0 0Columns in this examle represents the following:
- total: The total physical memory in the system (in kilobytes). In this example, the system has 1,008,588 KB (985 MB) of RAM.
- used: The amount of memory currently used by running processes.
- free: The memory that is completely unallocated.
- shared: Memory used by temporary shared memory segments.
- buff/cache: Memory used by the kernel for buffers and caches. Although this memory is marked as “used,” it is available to be reclaimed quickly when needed.
- available: An estimate of how much memory is available for new applications without swapping. This value includes both free memory and memory that can be quickly freed from the buffer/cache.
Difference Between Free and Available Memory
- Free Memory: This refers to the portion of RAM that is not being used at all. It is completely idle and unallocated. However, relying solely on this metric can be misleading because modern Linux systems deliberately use much of the free memory for caching to speed up system performance.
- Available Memory: This is a more meaningful metric for determining how much memory is truly available for applications. It not only accounts for the free memory but also includes the memory used for caching and buffers that can be quickly reclaimed. Therefore, even if the "free" memory appears low, a high "available" memory indicates that the system can still allocate memory for new processes without resorting to swap space.
fwupdate
This command is used to update the router's ICR-OS firmware.
Synopsis:
fwupdate [-i <filename> [-h] [-n]] [-f] [-c]Options:
| Option | Description |
|---|---|
-i <filename> | Path to the new ICR-OS firmware file. |
-h | Generate HTML output (used when called from the web interface). |
-n | Do not reboot after the firmware update. |
-f | Finish update procedures (called by default after the update). |
-c | Check firmware update status. |
Examples:
Update the firmware from a file:
fwupdate -i /tmp/firmware.binCheck the current firmware update status:
fwupdate -cid
This command is utilized to display user and group information for a specified user, or for the current user if no user is specified. It provides details such as user ID (UID), group ID (GID), and supplementary groups associated with the user.
Synopsis:
id [OPTIONS] [USER]Description:
By default, without options, the command prints the UID, GID, and supplementary groups of the specified user or the current user. The output includes both the IDs and the names of the user and groups.
Options:
| Option | Description |
|---|---|
-u | Prints the user ID of the specified user or the current user. |
-g | Prints the primary group ID of the specified user or the current user. |
-G | Prints all the supplementary group IDs of the specified user or the current user. |
-n | When used with -u, -g, or -G, prints the name(s) of the user or group(s) instead of the numeric ID(s). |
-r | Prints the real, rather than effective, user or group ID. |
Examples:
Print the current user's UID, GID, and supplementary groups:
idPrint the UID of the current user:
id -uPrint the primary group name of the user:
id -gnPrint all supplementary group names of the current user:
id -GnFor a comprehensive guide on the id command and its options, consult the man pages or official documentation available on your system or online.
kill
This command sends a signal to a running process, by default SIGTERM which requests graceful termination.
Synopsis:
kill [ -<signal> ] <process-id> [ <process-id> ... ]
kill -lOptions:
| Option | Description |
|---|---|
-l | Print a list of signal names. These are found in /usr/include/linux/signal.h. |
Examples:
End the process with PID 1234 by sending signal SIGTERM:
kill 1234End the process with PID 1234 by sending signal SIGKILL:
kill -9 1234killall
This command sends a signal to all processes matching the specified name, by default SIGTERM.
Synopsis:
killall [ -q] [ -<signal> ] <process-name> [<process-name> ...]Options:
| Option | Description |
|---|---|
-l | Print a list of signal names. These are found in /usr/include/linux/signal.h. |
-q | Do not complain if no processes were killed. |
Examples:
End all processes with name pppd by sending signal SIGTERM:
killall pppdEnd all processes with name pppd by sending signal SIGKILL:
killall -9 pppdklog
This command can be used to print the kernel logs.
Synopsis:
klogExamples:
Display the kernel log:
kloglogger
This program makes entries in the system log. It provides a shell command interface to the system log module.
Synopsis:
logger [ option ] [ message ... ]Options:
| Option | Description |
|---|---|
-i | Log the process id of the logger process with each line. |
-s | Log the message to standard error, as well as the system log. |
-f <file> | Log the specified file. |
-p <priority> | Enter the message with the specified priority. The priority may be specified numerically or as a facility.level pair. |
-t <tag> | Mark every line in the log with the specified tag. |
-u <socket> | Write to socket as specified with socket instead of built-in syslog routines. |
-d | Use a datagram instead of a stream connection to this socket. |
Examples:
Send the message "System rebooted" to the syslogd daemon:
logger System rebootedSend the message "System going down immediately!!!" to the syslog daemon, at the emerg level and user facility:
logger -p user.emerg "System going down immediately!!!"losetup
This program can be used to set up and control loop devices.
Synopsis:
losetup [-rP] [-o OFS] {-f|LOOPDEV} FILE
losetup -c LOOPDEV
losetup -d LOOPDEV
losetup -a
losetup -fOptions:
| Option | Description |
|---|---|
-o OFS | Start OFS bytes into FILE. |
-P | Scan for partitions. |
-r | Read-only. |
-f | Show/use next free loop device. |
mount
This program can be used to mount a file system.
Synopsis:
mount [-a] [-o] [-r] [-t] [-w] <DEVICE> <NODE> [ -o <option>, ...]Options:
| Option | Description |
|---|---|
-a | Mount all filesystems in fstab. |
-o | One of many filesystem options, listed below. |
-r | Mount the filesystem read-only. |
-t | Specify the filesystem type. |
-w | Mount for reading and writing (default). |
Filesystem Options:
| Option | Description |
|---|---|
async/sync | Writes are asynchronous/synchronous. |
atime/noatime | Enable/disable updates to inode access times. |
dev/nodev | Allow use of special device files/disallow them. |
exec/noexec | Allow use of executable files/disallow them. |
suid/nosuid | Allow set-user-id-root programs/disallow them. |
remount | Re-mount a mounted filesystem, changing its flags. |
ro/rw | Mount for read-only/read-write. |
bind | Bind a directory to an additional location. |
move | Relocate an existing mount point. |
Examples:
Connect the contents of a USB flash drive to the directory /mnt:
mount -t vfat /dev/sda1 /mntopenssl
The openssl program is a command line tool for using the various cryptography functions of OpenSSL's crypto library from the shell. It can be used for:
- Creation of RSA, DH and DSA key parameters
- Creation of X.509 certificates, CSRs and CRLs
- Calculation of Message Digests
- Encryption and Decryption with Ciphers
- SSL/TLS Client and Server Tests
- Handling of S/MIME signed or encrypted mail
Synopsis:openssl [<option> ...]
Options:
For detailed description of this command, visit Linux manual pages.
Examples:
Generate a new key for the SSH server.
openssl genrsa -out /etc/certs/ssh_rsa_key 512Generate a new certificate for the HTTPS server.
openssl req -new -out /tmp/csr -newkey rsa:1024 -nodes -keyout /etc/certs/https_key
openssl x509 -req -setstart 700101000000Z -setend 400101000000Z -in /tmp/csr -signkey /etc/certs/https_key -out /etc/certs/https_certpasswd
This program can be used to change user passwords. A user with the User role can change only their own password. A user with the root role can change passwords for all users.
Synopsis:passwd [options] [LOGIN]
Options:
| Option | Description |
|---|---|
-a, --all | Report password status on all accounts |
-d, --delete | Delete the password for the named account |
-e, --expire | Force expire the password for the named account |
-h, --help | Display this help message and exit |
-k, --keep-tokens | Change password only if expired |
-i, --inactive INACTIVE | Set password inactive after expiration to INACTIVE |
-l, --lock | Lock the password of the named account |
-n, --mindays MIN_DAYS | Set minimum number of days before password change to MIN_DAYS |
-q, --quiet | Quiet mode |
-r, --repository REPOSITORY | Change password in REPOSITORY repository |
-R, --root CHROOT_DIR | Directory to chroot into |
-P, --prefix PREFIX_DIR | Directory prefix |
-S, --status | Report password status on the named account |
-u, --unlock | Unlock the password of the named account |
-w, --warndays WARN_DAYS | Set expiration warning days to WARN_DAYS |
-x, --maxdays MAX_DAYS | Set maximum number of days before password change to MAX_DAYS |
-s, --stdin | Read new token from stdin |
Examples:
Change the password for the logged-in user john.
$ passwd
Changing password for john.
Current password:
New password:
Retype new password:
passwd: password updated successfullyAdministrator is changing the password for the john user. This operation is not permitted to a user with the User role.
# passwd john
New password:
Retype new password:
passwd: password updated successfullypidof
This program lists the PIDs of all processes with names that match the names on the command line.
Synopsis:pidof <process-name> [<option>] [<process-name> ...]
Options:
| Option | Description |
|---|---|
-s | Display only a single PID. |
ps
This command displays information about currently running processes.
Synopsis:
ps [options]Options:
| Option | Description |
|---|---|
-w | Wide output (use twice for unlimited width). |
-a | Show all processes except session leaders. |
-e | Select all processes. |
Examples:
Display currently running processes:
psDisplay all processes with wide output:
ps -wwrestore
This command restores the router configuration from a previously created backup file. The backup file can be generated using the backup command, see Chapter backup.
Synopsis:
restore [-p <password>] <filename>Options:
| Option | Description |
|---|---|
-p <password> | Decrypt the backup file before restoring. Use this option when the backup was created with the -p option. |
Tips
After a successful restore, the router typically prints Done. and may reboot automatically to apply the new configuration.
Examples:
Restore configuration from a file:
restore /tmp/my.cfgRestore an encrypted backup file:
restore -p MySecretPass /tmp/backup.encTips
Typical output messages after running restore:
Configuration remains unchanged.File not found.Decryption of configuration failed.Configuration successfully updated.
rlog
This command can be used to print the emergency logs.
Synopsis:
rlogExamples:
Display the emergency log:
rlogslog
This command prints the system log from /var/log/messages.
Synopsis:
slog [-n <number>] [-f]Options:
| Option | Description |
|---|---|
-n <number> | Print the last N lines instead of the default 10. |
-f | Follow the log output as new entries are added. |
Examples:
Print the last 20 lines of the system log:
slog -n 20Follow the system log in real time:
slog -fservice
This command starts, stops, or restarts a specified system service.
Synopsis:
service <service_name> <start | stop | restart>Tips
To list the available services, run: ls /etc/init.d/
Examples:
Start the cron service:
service cron startRestart the syslog service:
service syslog restartStop the ppp service:
service ppp stopsudo
This command is not supported by the ICR-OS from version 6.2.8 anymore. For compatibility reasons, the sudo command is just a symlink to the doas command.
sysctl
This program can be used to list and modify kernel parameters at runtime. The parameters available are those listed under /proc/sys/.
Synopsis:sysctl -p [-enq] [FILE...] / [-enqaw] [KEY[=VALUE]]...
Options:
| Option | Description |
|---|---|
-p | Set values from FILEs (default /etc/sysctl.conf). |
-e | Ignore errors about unknown keys. |
-n | Disable printing of the key name when printing values. |
-q | Quiet mode, don't display the values set to stdout. |
-a | Display all values currently available. |
-w | Use this option when all arguments prescribe a key to be set. |
Examples:
Return the value of kernel.hostname kernel parameter, don't print the key name.
sysctl -n kernel.hostname
RouterSet the value of kernel.hostname kernel parameter to "example.com".
sysctl -w kernel.domainname="example.com"
kernel.domainname = example.comtimes
This command is a shell builtin that provides information on the accumulated user and system times for the current shell and all of its child processes. It is an essential tool for evaluating the performance of scripts, helping users and administrators gauge the resource usage and efficiency of their commands or scripts executed within the shell.
Synopsis:
timesExamples:
Display accumulated shell and child process times:
timesOutput:
0m0.020s 0m0.070s
0m0.130s 0m0.260stop
Warning
This command displays only free memory, not available memory. For more information, refer to command free.
This program provides a dynamic real-time view of a running system. It can display system summary information, as well as a list of processes or threads currently being managed by the kernel.
Synopsis:top [-b] [-nCOUNT] [-dSECONDS]
Options:
| Option | Description |
|---|---|
-b | Batch mode - could be useful for sending output from top to other programs or to a file. In this mode, top will not accept input and runs until the iterations limit you've set with the '-n' command-line option, or until killed. |
-nCOUNT | Exit after N iterations. |
-dSECONDS | Delay between updates in secs format. |
Keys:
| Key | Description |
|---|---|
n/m/p/t | Sort by pid/mem/cpu/time |
r | Reverse sort |
q, ^C | Exit |
Examples:
Run top program in batch mode and exit after 5 iterations.
top -b -n5Run top program and update the output every 10 seconds. Exit by q key.
top -d10umask
This command is a built-in shell command used to set the default permission or file mode creation mask. The setting of the umask determines the permissions that are not set on newly created files and directories. This command is crucial for controlling the default file permissions and ensuring security by restricting the default set of permissions when new files or directories are created.
Synopsis:umask [OPTION]... [MODE]
Description:umask is used without any arguments to display the current umask value in a shell session. The umask can be set by providing an octal or symbolic value representing the set of permissions to mask out (i.e., permissions that won't be set on new files and directories). For example, a umask of 022 prevents new files from being created with write permissions for group and others.
Options:
-S: Display the current umask in a symbolic format, which can be more understandable than the default octal representation.-p: Display the output in a format that can be reused as input, facilitating the replication of umask settings in scripts or session initializations.
Examples:
Display the current umask value:
umaskSet a new umask value using octal notation:
umask 077This command configures the shell so that new files and directories are created with permissions allowing only the owner to read, write, and execute them, while preventing group and others from any access.
Display the current umask in a symbolic format:
umask -SSetting the umask is an essential part of system administration and security, as it helps ensure that files and directories are not inadvertently created with overly permissive or restrictive permissions.
This section aims to provide a clear understanding of how the umask command functions, its syntax, options, and usage examples to guide users in managing default permissions effectively.
umount
This program can be used to umount file systems.
Synopsis:umount [-a] [-r] [-l] [-f] <file system> | <directory>
Options:
| Option | Description |
|---|---|
-a | Unmount all file systems |
-r | Try to remount devices as read-only if mount is busy |
-l | Lazy umount (detach filesystem) |
-f | Force umount (i.e. unreachable NFS server) |
Examples:
Disconnecting the disc connected to the directory /mnt.
umount /mntumupdate
This program can be used for adding or deleting of a router app from the command line.
Synopsis:umupdate [-a <filename>] [-d <name>]
Options:
| Option | Description |
|---|---|
-a | Add new or update installed router app. Enter path to the installation file. |
-d | Delete an installed router app with the specified name. List of installed router apps can be obtained by service module list command. |
Network Commands
Networking commands facilitate the configuration and troubleshooting of network settings. These tools are essential for managing connections, analyzing traffic, and ensuring secure communication over the network.
arp
This program displays and modifies the Internet-to-Ethernet address translation tables used by the address resolution protocol.
Synopsis:
arp [-a <hostname>] [-s <hostname> <hw_addr>] [-d <hostname>] [-v] [-n] [-i <if>] [-D <hostname>] [-A ] [-f <filename>]Options:
| Option | Description |
|---|---|
-a | The entries will be displayed in alternate (BSD) style. |
-s | Manually create an ARP address mapping entry for host hostname with hardware address set to hw_addr. |
-d | Remove any entry for the specified host. |
-v | Tell the user what is going on by being verbose. |
-n | Shows numerical addresses instead of trying to determine symbolic host, port or user names. |
-i | Select an interface. |
-D | Use the interface ifa's hardware address. |
-f | Similar to the -s option, only this time the address info is taken from file filename set up. The name of the data file is very often /etc/ethers, but this is not official. If no filename is specified /etc/ethers is used as default. The format of the file is simple; it only contains ASCII text lines with a hardware address and a hostname separated by whitespace. Additionally the pub, temp and netmask flags can be used. |
With no flags, the program displays the current ARP entry for hostname. The host may be specified by name or by number, using Internet dot notation. For a detailed description of this command, visit the Linux manual pages.
Examples:
arp -nbrctl
Tips
The brctl command is a legacy utility for managing Ethernet bridges. While retained for backward compatibility, it is considered deprecated. For new configurations, especially those involving VLANs or Distributed Switch Architecture (DSA), it is strongly recommended to use the modern ip and bridge commands. brctl does not support advanced features like VLAN filtering.
This command sets up, maintains, and inspects the Ethernet bridge configuration in the Linux kernel.
An Ethernet bridge is a device commonly used to connect different networks of Ethernets together so that these Ethernets appear as one Ethernet to the participants.
Synopsis:
brctl [<commands>]Options:
| Command | Parameters | Description |
|---|---|---|
addbr | <bridge> | Add bridge |
delbr | <bridge> | Delete bridge |
addif | <bridge> <device> | Add interface to bridge |
delif | <bridge> <device> | Delete interface from bridge |
setageing | <bridge> <time> | Set ageing time |
setbridgepri | <bridge> <prio> | Set bridge priority |
setfd | <bridge> <time> | Set bridge forward delay |
sethello | <bridge> <time> | Set hello time |
setmaxage | <bridge> <time> | Set max message age |
setpathcost | <bridge> <port> <cost> | Set path cost |
setportrpio | <bridge> <port> <prio> | Set port priority |
show | Show list of bridges | |
showmacs | <bridge> | Show list of MAC addresses |
showstp | <bridge> | Show bridge STP info |
stp | <bridge> {on | off} | Turn STP on/off |
Examples:
Create bridge br0 and add two interfaces to it:
brctl addbr br0
brctl addif br0 eth0
brctl addif br0 eth1bridge
The bridge command is the modern utility for managing Ethernet bridges, including advanced features such as VLAN filtering. It is part of the iproute2 package and is the recommended replacement for the deprecated brctl command.
Synopsis:
bridge [global options] <object> <command> [options]Global Options:
| Option | Description |
|---|---|
-V | Print the version of the bridge utility. |
-s | Display statistics. |
-n <netns> | Switch to the specified network namespace. |
-j | Output in JSON format. |
-p | Pretty-print JSON output. |
Objects:
| Object | Description |
|---|---|
link | Manage bridge port settings. |
fdb | Manage the forwarding database (MAC address table). |
vlan | Manage VLAN filters on bridge ports. |
mdb | Manage the multicast database. |
Examples:
Show all bridge interfaces and their ports:
bridge link showAdd a VLAN to a bridge port:
bridge vlan add vid 10 dev eth0Show VLANs on all bridge ports:
bridge vlan showShow the forwarding database:
bridge fdb showconntrack
This program is the user interface to the netfilter connection tracking system.
Synopsis:
conntrack [commands] [option]Options:
| Command | Description |
|---|---|
-L [table] [option] | List conntrack or expectation table |
-G [table] | Get conntrack or expectation |
-D [table] | Delete conntrack or expectation |
-I [table] | Create a conntrack or expectation |
-U [table] | Update a conntrack |
-E [table] | Show events |
-F [table] | Flush table |
Tables:
| Table | Description |
|---|---|
conntrack | This is the default table. It contains a list of all currently tracked connections through the system. |
expect | This is the table of expectations. Connection tracking expectations are the mechanism used to "expect" RELATED connections to existing ones. |
Options:
| Option | Description |
|---|---|
-n <ip> | Source NAT ip |
-g <ip> | Destination NAT ip |
-m <mark> | Set mark |
-e <eventmask> | Event mask, eg. NEW,DESTROY |
-z | Zero counters while listing |
-o <type[...]> | Output format, eg. xml |
Examples:
conntrack -L
conntrack -Fcurl
curl (Client URL) is a versatile tool for transferring data to or from a server. It supports a wide range of protocols including HTTP, HTTPS, FTP, FTPS, SCP, SFTP, SMTP, and more. It is an alternative to wget, see Chapter wget.
Synopsis:
curl [options...] <url>Common Options:
| Option | Description |
|---|---|
-o <file> | Write output to <file> instead of stdout. |
-O | Save the remote file using its original filename. |
-I | Fetch HTTP headers only (HEAD request). |
-L | Follow redirects. |
-k | Allow connections to SSL sites without valid certificates. |
-u <user:pwd> | Specify the username and password for server authentication. |
For the full list of options, run curl --help or refer to the curl man page.
Examples:
Download a file and save it with its original name:
curl -O https://example.com/firmware.binFetch only the HTTP headers from a URL:
curl -I https://example.comDownload a file with authentication:
curl -u admin:password -O https://example.com/config.cfgdig
dig (Domain Information Groper) is a command-line tool for querying DNS name servers. It is useful for troubleshooting DNS problems and for performing DNS lookups.
Tips
The dig tool was added in firmware version 6.6.1.
Synopsis:
dig [@server] [name] [type] [options]Options:
| Option | Description |
|---|---|
@<server> | Specify the DNS server to query. If omitted, the system's default resolver is used. |
<name> | The domain name to look up. |
<type> | The DNS record type to query (e.g., A, AAAA, MX, NS, TXT, SOA). Default is A. |
-x <addr> | Perform a reverse DNS lookup for the specified IP address. |
+short | Display a terse answer. |
+noall +answer | Display only the answer section. |
+tcp | Use TCP instead of UDP for the query. |
-p <port> | Query the DNS server on the specified port (default: 53). |
-4 | Force the use of IPv4. |
-6 | Force the use of IPv6. |
Examples:
Look up the A record for a domain:
dig example.comLook up the MX records for a domain:
dig example.com MXQuery a specific DNS server:
dig @8.8.8.8 example.comPerform a reverse DNS lookup:
dig -x 8.8.8.8Display a short answer only:
dig +short example.comLook up the NS records for a domain:
dig example.com NS +noall +answerdhcrelay
The Dynamic Host Configuration Protocol (DHCP) Relay Agent, dhcrelay, provides a means for relaying DHCP and BOOTP requests from a subnet to which no DHCP server is directly connected to one or more DHCP servers on other subnets. It supports both DHCPv4/BOOTP and DHCPv6 protocols (v3 routers only).
Synopsis:
dhcrelay [-4] [-d] [-q] [-a] [-D] [-A <length>] [-c <hops>] [-p <port>] [-pf <pid-file>] [--no-pid] [-m append|replace|forward|discard] [-i interface0 [ ... -i interfaceN] server0 [ ... serverN]
dhcrelay -6 [-d] [-q] [-I] [-c <hops>] [-p <port>] [-pf <pid-file>] [--no-pid] [-l lower0 [ ... -l lowerN] -u upper0 [ ... -u upperN]Options:
| Option | Description |
|---|---|
-a | Append an agent option field to each request before forwarding it to the server. Agent option fields in responses sent from servers to clients will be stripped before forwarding such responses back to the client. |
-A <length> | Specify the maximum packet size to send to a DHCPv4/BOOTP server. This might be done to allow sufficient space for addition of relay agent options while still fitting into the Ethernet MTU size. |
-D | Drop packets from upstream servers if they contain Relay Agent Information options that indicate they were generated in response to a query that came via a different relay agent. |
-i <ifname> | Listen for DHCPv4/BOOTP queries on interface ifname. Multiple interfaces may be specified by using more than one -i option. If no interfaces are specified on the command line, dhcrelay will identify all network interfaces, eliminating non-broadcast interfaces if possible, and attempt to listen on all of them. |
-m <option> | Control the handling of incoming DHCPv4 packets which already contain relay agent options. |
Examples:
dhcrelay -i eth1 -i eth0 <server ip>ebtables
This program can be used as an administration tool for firewall IP packets filtering. It enables transparent filtering of network traffic passing through a Linux bridge. The filtering possibilities are limited to link layer filtering and some basic filtering on higher network layers. Advanced logging, MAC DNAT/SNAT and brouter facilities are also included.
The ebtables tool can be combined with the other filtering tools (iptables and ip6tables) to make a bridging firewall that is also capable of filtering these higher network layers.
Synopsis:
ebtables -[ADI] chain rule-specification [options]
ebtables -P chain target
ebtables -[LFZ] [chain]
ebtables -[NX] [chain]
ebtables -E old-chain-name new-chain-nameCommands:
| Command | Description |
|---|---|
--append -A chain | Append to chain |
--delete -D chain | Delete matching rule from chain |
--delete -D chain rulenum | Delete rule at position rulenum from chain |
--change-counters -C chain [rulenum] pcnt bcnt | Change counters of existing rule |
--insert -I chain rulenum | Insert rule at position rulenum in chain |
--list -L [chain] | List the rules in a chain or in all chains |
--flush -F [chain] | Delete all rules in chain or in all chains |
--init-table | Replace the kernel table with the initial table |
--zero -Z [chain] | Put counters on zero in chain or in all chains |
--policy -P chain target | Change policy on chain to target |
--new-chain -N chain | Create a user defined chain |
--rename-chain -E old new | Rename a chain |
--delete-chain -X [chain] | Delete a user defined chain |
--atomic-commit | Update the kernel w/t table contained in <FILE> |
--atomic-init | Put the initial kernel table into <FILE> |
--atomic-save | Put the current kernel table into <FILE> |
--atomic-file file | Set <FILE> to file |
Options:
| Option | Description |
|---|---|
--proto -p [!] proto | Protocol hexadecimal, by name or LENGTH |
--src -s [!] address[/mask] | Source mac address |
--dst -d [!] address[/mask] | Destination mac address |
--in-if -i [!] name[+] | Network input interface name |
--out-if -o [!] name[+] | Network output interface name |
--logical-in [!] name[+] | Logical bridge input interface name |
--logical-out [!] name[+] | Logical bridge output interface name |
--set-counters -c chain pcnt bcnt | Set the counters of the to be added rule |
--modprobe -M program | Try to insert modules using this program |
--concurrent | Use a file lock to support concurrent scripts |
--version -V | Print package version |
Environment variable:EBTABLES_ATOMIC_FILE — if set <FILE> (see above) will equal its value.
Standard targets: DROP, ACCEPT, RETURN or CONTINUE; The target can also be a user defined chain.
Supported chains for the filter table: INPUT FORWARD OUTPUT
The program can be used for sending email.
Attention: To work properly, this command requires the SMTP service to be configured correctly. Refer to the Configuration Manual of your router, chapter Configuration → Services → SMTP.
Synopsis:
email -t <to> [-s <subject>] [-m <message>] [-a <attachment>] [-r <retries>]Options:
| Option | Description |
|---|---|
-t | E-mail address of the recipient |
-s | Subject, enter the subject in quotation marks |
-m | Message, enter the message in quotation marks |
-a | Attachment file of the email |
-r | Number of attempts to send the e-mail (default value: 2) |
Examples:
email -t john.doe@email.com -s "System Log" -a /var/log/messagesether-wake
This command sends a "magic packet" to wake up a machine that is powered down but has a network interface with Wake-on-LAN enabled.
Synopsis:
ether-wake [-b] [-i IFACE] [-p aa:bb:cc:dd[:ee:ff]] MACOptions:
| Option | Description |
|---|---|
MAC | MAC address of the target machine (required). |
-b | Send the magic packet as a broadcast instead of directed to the target MAC. |
-i IFACE | Network interface to send the packet through (default: eth0). |
-p PASSWORD | Append a 4- or 6-byte password to the magic packet (some NICs require this). |
Examples:
Wake up a machine with MAC address 00:11:22:33:44:55:
ether-wake 00:11:22:33:44:55Wake up using a specific interface:
ether-wake -i eth1 00:11:22:33:44:55Wake up with broadcast and password:
ether-wake -b -p 00:11:22:33:44:55 00:11:22:33:44:55ethtool
This command can be used to display or change Ethernet card settings.
Synopsis:
ethtool [<option> ...] <devname> [<commands>]Options:
For a detailed description of this command, visit the Linux manual pages.
Examples:
ethtool eth0
ethtool -s eth0 speed 10 duplex half autoneg off
ethtool -s eth0 autoneg onftpput
This command facilitates uploading files to an FTP server. It is designed for simplicity and embedded environments, offering essential functionality for transferring files over FTP.
Usage:
ftpput [OPTIONS] HOST [REMOTE_FILE] LOCAL_FILEDescription:
This command uploads LOCAL_FILE from the local system to the specified HOST. The file on the host can be specified with [REMOTE_FILE]; if not provided, the name of the LOCAL_FILE is used on the remote server.
Options:
-v: Enables verbose output, providing additional details during the file transfer process.-u USER: Specifies the username for authentication with the FTP server.-p PASS: Specifies the password for authentication with the FTP server.-P PORT: Specifies the port on which to connect to the FTP server. If not provided, the standard FTP port (21) is used.
Examples:
ftpput -u username -p password ftp.example.com /remote/path/file.txt /local/path/file.txt
ftpput -v -u username -p password -P 21 ftp.example.com /remote/file.txt /local/file.txtFor more detailed information about using ftpput, refer to the official BusyBox documentation or the built-in help by executing ftpput --help in the terminal.
hostname
Tips
The router hostname can also be set in the web GUI under Administration → Router Name.
This command displays or sets the hostname of the system.
Synopsis:
hostname [-b]Options:
| Option | Description |
|---|---|
-b | Set hostname to localhost if the current hostname is not valid (does not contain at least one dot). |
Examples:
Display the current hostname:
hostnameOutput:
Routerifconfig
This command can be used to configure a network interface.
Synopsis:
ifconfig [-a] <interface> [<option> ...]Options:
| Option | Description |
|---|---|
broadcast <addr.> | If the address argument is given, set the protocol broadcast address for this interface. |
pointtopoint <ad.> | This keyword enables the point-to-point mode of an interface, meaning that it is a direct link between two machines with nobody else listening on it. |
netmask <address> | Set the IP network mask for this interface. |
dstaddr <address> | Set the remote IP address for a point-to-point link (such as PPP). |
metric <NN> | This parameter sets the interface metric. |
mtu <NN> | This parameter sets the Maximum Transfer Unit of an interface. |
trailers | This flag used to cause a non-standard encapsulation of inet packets on certain link levels. |
arp | Enable or disable the use of the ARP protocol on this interface. |
allmulti | Enable or disable all-multicast mode. If selected, all multicast packets on the network will be received by the interface. |
multicast | Set the multicast flag on the interface. This should not normally be needed as the drivers set the flag correctly themselves. |
promisc | Enable or disable the promiscuous mode of the interface. If selected, all packets on the network will be received by the interface. |
txqueuelen <NN> | Set the length of the transmit queue of the device. |
| `up | down` |
Tips
Changes made with ifconfig are immediate but temporary. They will be lost after a system reboot unless they are also updated in the router's permanent configuration files or via the GUI.
Examples:
Display the status of all network interfaces:
ifconfigBring up the loopback interface:
ifconfig lo upConfigure a virtual interface with a static IP:
ifconfig eth0:0 192.168.2.1 netmask 255.255.255.0 upSet the MAC address of an interface:
ifconfig eth0 hw ether 00:11:22:33:44:55ip
The ip command is a powerful tool for network interface configuration, routing, and tunnel management. It serves as a modern replacement for the older ifconfig, route, and arp utilities. Type ip --help for help in the terminal.
Synopsis:
ip [ <options> ] <object> { <command> | help }Options:
| Option | Description |
|---|---|
-V[ersion] | Print the version of the ip utility and exit |
-s[tatistics] | Output more information. If the option appears twice or more, the amount of information increases. |
-r[esolve] | Use the system's name resolver to print DNS names instead of host addresses |
-f[amily] <family> | Specifies the protocol family to use. The protocol family identifier can be one of inet, inet6, bridge, ipx, dnet or link. |
-o[neline] | Output each record on a single line, replacing line feeds with the '' character |
Objects:
| Object | Description |
|---|---|
link | Network device |
addr | Protocol (IP or IPv6) address on a device |
route | Routing table entry |
rule | Rule in routing policy database |
neigh | Manage ARP or NDISC cache entries |
tunnel | Tunnel over IP |
maddr | Multicast address |
mroute | Multicast routing cache entry |
monitor | Watch for netlink messages |
xfrm | Manage IPSec policies |
Examples:
ip addr show
ip route add 192.168.3.0/24 via 192.168.1.2
ip link set eth1 downipcalc
This utility is designed to calculate and display various network settings based on an IP address and optionally a netmask or prefix length. It is a valuable tool for network administrators and anyone needing to quickly derive network configuration details.
Usage:
ipcalc [-bnmphs] ADDRESS[/PREFIX] [NETMASK]Description:ipcalc takes an IP address, and optionally a slash notation prefix or a netmask, and calculates the resulting broadcast, network, netmask, and IP prefix. It simplifies network configuration and planning tasks.
Options:
| Option | Description |
|---|---|
-b | Displays the broadcast address for the given IP network. |
-n | Calculates and displays the network address. |
-m | Shows the default netmask for the provided IP address. |
-p | Displays the prefix length for the given IP address/netmask. |
-h | Resolves and shows the hostname associated with the IP address. |
-s | Suppresses error messages, making the output cleaner in scripts or batch operations. |
Examples:
Calculate network information for 192.168.1.100/24:
ipcalc -bnmp 192.168.1.100/24Output:
NETMASK=255.255.255.0
BROADCAST=192.168.1.255
NETWORK=192.168.1.0
PREFIX=24Show the default netmask for an address:
ipcalc -m 192.168.1.100Output:
NETMASK=255.255.255.0iptables
This program can be used as an administration tool for IP packets filtering and NAT.
Synopsis:
iptables [<options>]Options:
For a detailed description of this command, type iptables -h or visit iptables manual pages.
Key Features & Supported Modules:
The router's iptables includes support for several advanced modules:
- DSCP & QoS — Match and set DSCP (Differentiated Services Code Point) values for quality-of-service traffic shaping using
-m dscpand-j DSCP. - CONNMARK — Mark connections and use marks in routing decisions using
-j CONNMARKand-m connmark. - String Match — Match packet payloads against a string pattern using
-m string. - U32 Match — Perform arbitrary bit-level matching on packet headers using
-m u32. - Statistic Module — Apply rules only to a statistical subset of packets using
-m statistic.
To list available match modules:
cat /proc/net/ip_tables_matchesExamples:
# Port forwarding: redirect external port 8080 to internal host port 80
/sbin/iptables -t nat -A pre_nat -p tcp --dport 8080 -j DNAT --to-destination 192.168.1.11:80
/sbin/iptables -t mangle -A pre_nat -p tcp --dport 8080 -j ACCEPT
# Set DSCP value for traffic shaping
iptables -t mangle -I POSTROUTING -p tcp --dport 81 -j DSCP --set-dscp 0x0a
iptables -t mangle -I POSTROUTING -m dscp --dscp 0x0a -j MARK --set-mark 81iw
This program is used for displaying and manipulating wireless devices and their configuration.
Synopsis:
iw [options] commandOptions:
For more details, see iw manual page.
Commands:
| Command | Description |
|---|---|
dev | List all devices or specify a device to manipulate. |
link | Display the status of the current link. |
scan | Trigger a scan and dump the results. |
station dump | Show information about all stations. |
interface add | Add a new virtual interface. |
phy | Show information about physical devices. |
Examples:
iw dev wlan0 scan
iw dev wlan0 link
iw dev wlan0 station dump
iw phy phy0 info
iw dev wlan0 interface add wlan1 type monitornc
The nc (netcat) program can be used to open a pipe to IP:port.
Synopsis:
nc [OPTIONS] HOST PORT : connect
nc [OPTIONS] -l -p PORT [HOST] [PORT] : listenOptions:
| Option | Description |
|---|---|
-e | PROG Run PROG after connect (must be last) |
-l | Listen mode, for inbound connects |
-lk | With -e, provides persistent server |
-p PORT | Local port number |
-s ADDR | Local address |
-w SEC | Timeout for connects and final net reads |
-i SEC | Delay interval for lines sent |
-n | Don't do DNS resolution |
-u | UDP mode |
-b | Allow broadcasts |
-v | Verbose |
-o FILE | Hex dump traffic |
-z | Zero-I/O mode (scanning) |
Example:
nc -p 31337 -w 5 192.168.3.1 42net-snmpinform
This command is designed to send SNMP INFORM messages to a management entity. It supports SNMP versions 1, 2c, and 3, offering a reliable way to notify management systems of significant events.
Synopsis:
net-snmpinform [OPTIONS] AGENT TRAP-PARAMETERSOptions:
| Option | Description |
|---|---|
-v 1|2c|3 | SNMP version to use. |
-c COMMUNITY | SNMP community string. |
-a PROTOCOL | Authentication protocol (MD5 or SHA, for SNMPv3). |
-A PASSPHRASE | Authentication passphrase (for SNMPv3). |
-l LEVEL | Security level: noAuthNoPriv, authNoPriv, or authPriv (for SNMPv3). |
-u USER-NAME | Security name (for SNMPv3). |
For more details, see the snmpinform(1) - Linux man page.
Examples:
net-snmpinform -v 2c -c public AGENT '' 0 .1.3.6.1.6.3.1.1.5.2
net-snmpinform -v 3 -u myUser -l authPriv -a SHA -A myAuthPass -x DES -X myPrivPass AGENT '' 0 .1.3.6.1.6.3.1.1.5.3
net-snmpinform -v 1 -c public AGENT .1.3.6.1.4.1.8072.2.3.2.1 0 .1.3.6.1.4.1.8072.2.3.2.2 6net-snmptrap
This command is used to send SNMP trap messages to a management entity. It supports SNMP versions 1, 2c, and 3.
Synopsis:
net-snmptrap [OPTIONS] AGENT TRAP-PARAMETERSOptions:
| Option | Description |
|---|---|
-v 1|2c|3 | SNMP version to use. |
-c COMMUNITY | SNMP community string. |
-a PROTOCOL | Authentication protocol (MD5 or SHA, for SNMPv3). |
-A PASSPHRASE | Authentication passphrase (for SNMPv3). |
-l LEVEL | Security level: noAuthNoPriv, authNoPriv, or authPriv (for SNMPv3). |
-u USER-NAME | Security name (for SNMPv3). |
-C i | Send an INFORM instead of a TRAP (SNMPv2c/v3). |
For more details, see the snmptrap(1) - Linux man page.
Examples:
net-snmptrap -v 2c -c public AGENT '' 0 .1.3.6.1.4.1.8072.2.3.0.1 0 0 ''
net-snmptrap -v 3 -u myUser -l authPriv -a SHA -A myAuthPass -x DES -X myPrivPass AGENT '' 0 .1.3.6.1.6.3.1.1.5.1
net-snmptrap -v 2c -c public -C i AGENT '' 0 .1.3.6.1.4.1.8072.2.3.0.2 0 0 ''netstat
This program can be used to display the networking information.
Synopsis:
netstat [<options>]Options:
| Option | Description |
|---|---|
-l | Display listening server sockets |
-a | Display all sockets (default: connected) |
-e | Display other/more information |
-n | Don't resolve names |
-r | Display routing table |
-t | TCP sockets |
-u | UDP sockets |
-w | Raw sockets |
-x | Unix sockets |
Examples
List all listening TCP and UDP ports numerically:
netstat -tulnPrint the routing table:
netstat -rnnsupdate
This program reads instructions from a specified filename or standard input and uses the DNS dynamic update protocol to add or delete resource records from a zone maintained by a name server that is configured to allow dynamic updates.
Synopsis:
nsupdate [-d] [-D] [-g] [-i] [-k keyfile] [-l] [-L level] [-o] [-p port]
[-q] [-r udpretries] [-R randomdev] [-t timeout] [-T] [-u udptimeout]
[-v] [-V] [-y [hmac:]keyname:secret] [filename]Options:
| Option | Description |
|---|---|
-d | Enable debug mode. |
-k keyfile | TSIG key file for authentication. |
-v | Use TCP instead of UDP (useful for large updates). |
-y [hmac:]keyname:secret | Specify TSIG key inline. |
-p port | Use the specified port (default: 53). |
-t timeout | Set the timeout for DNS responses. |
Examples:
Update a DNS record using a TSIG key:
nsupdate -k /etc/named/keys/update.keyDelete a record interactively:
nsupdate
> server 192.168.1.1
> zone example.com
> update delete old.example.com A
> sendntpdate
This program can be used to set the system time from an NTP server.
Synopsis:
ntpdate [-p <probes>] [-t <timeout>] <server>Options:
| Option | Description |
|---|---|
-p | Specify the number of samples to be acquired from each server as the integer samples, with values from 1 to 8 inclusive. |
-t | Specify the maximum time waiting for a server response as the value timeout, in seconds and fraction. |
Examples:
ntpdate time.windows.comping
This program can be used to send ICMP echo requests to a network host.
Synopsis:
ping [OPTIONS] HOSTOptions:
| Option | Description |
|---|---|
-4,-6 | Force IP or IPv6 name resolution. |
-c CNT | Send only CNT pings. |
-s SIZE | Send SIZE data bytes in packets (default = 56). |
-i SECS | Interval. |
-A | Ping as soon as reply is received. |
-t TTL | Set TTL. |
-I IFACE/IP | Source interface or IP address. |
-W SEC | Seconds to wait for the first response (default 10). After all -c CNT packets are sent. |
-w SEC | Seconds until ping exits (default: infinite). Can exit earlier with -c CNT. |
-q | Quiet mode, only displays output at start and when finished. |
-p HEXBYTE | Payload pattern. |
Examples:
ping -c 1 -s 500 10.0.0.1ping6
This command is designed for diagnosing IPv6 network connections by sending ICMP ECHO_REQUEST packets to a specified host. It is a useful tool for testing the reachability of hosts on an IPv6 network and measuring the round-trip time for messages sent from the originating host to a destination computer.
Usage:
ping6 [OPTIONS] HOSTDescription:
Sends ICMP ECHO_REQUEST packets to the HOST specified as an argument. By default, ping6 sends packets until interrupted. If the host is reachable and responding, ping6 displays the time taken for the round-trip.
Options:
-c CNT: Stop after sendingCNTpings.-s SIZE: Specifies the number of data bytes to be sent.-i SECS: WaitSECSseconds between sending each packet.-A: Ping the host as soon as the reply is received.-I IFACE/IP: Use the specified interface or IP address as the source.-W SEC: Time to wait for the first response before timing out.-w SEC: Timeout beforeping6exits, regardless of how many packets have been sent or received.-q: Operate in quiet mode, only displaying summary lines at startup and completion.-p HEXBYTE: Pattern to use for payload data.
Examples:
ping6 -c 4 fe80::1
ping6 -i 2 -s 120 fe80::1The ping6 command is essential for network administrators and users who need to verify IPv6 connectivity or diagnose IPv6 network problems.
route
This program can be used to show and manipulate the IP routing table.
Synopsis:
route [ -n ] [ -e ] [ -A ] [ add | del | delete ]Options:
| Option | Description |
|---|---|
-n | Don't resolve names |
-e | Display other/more information |
-A | Select address family |
For a detailed description of this command, visit the Linux manual pages.
Examples:
route -n
route add -net 192.168.3.0/24 dev eth0
route add -host 192.168.3.1 gw 192.168.1.2
route add default gw 192.168.1.2scp
This program can be used for secure file transferring between hosts on a network. It uses the ssh protocol for data transfer with the same authentication and security.
Synopsis:
scp [-12346BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file] [-l limit] [-o ssh_option] [-P port] [-S program] [[user@]host1:]file1 ... [[user@]host2:]file2Options:
| Option | Description |
|---|---|
-1 | Forces scp to use protocol 1. |
-2 | Forces scp to use protocol 2. |
-4 | Forces scp to use IPv4 addresses only. |
-6 | Forces scp to use IPv6 addresses only. |
-B | Selects batch mode (prevents asking for passwords or passphrases). |
-C | Compression enable. Passes the -C flag to ssh to enable compression. |
-c cipher | Selects the cipher to use for encrypting the data transfer. This option is directly passed to ssh. |
-F ssh_config | Specifies an alternative per-user configuration file for ssh. This option is directly passed to ssh. |
-i identity_file | Selects the file from which the identity (private key) for public key authentication is read. This option is directly passed to ssh. |
-l limit | Limits the used bandwidth, specified in Kbit/s. |
-o ssh_option | Can be used to pass options to ssh in the format used in ssh_config. |
-P port | Specifies the port to connect to on the remote host. |
-p | Preserves modification times, access times, and modes from the original file. |
-q | Quiet mode: disables the progress meter as well as warning and diagnostic messages from ssh. |
-r | Recursively copy entire directories. Note that scp follows symbolic links encountered in the tree traversal. |
-S program | Name of program to use for the encrypted connection. The program must understand ssh options. |
-v | Verbose mode. Causes scp and ssh to print debugging messages about their progress. |
Examples:
scp root@remotehost.edu:/etc/version ~/myFolder
scp /etc/version root@remotehost.edu:~/
scp -r /home/user root@remotehost.edu:/tmp/barsipcalc
This command is an advanced console-based IP subnet calculator. It is capable of handling both IPv4 and IPv6 addressing schemes. It provides detailed information about network addresses, subnet masks, and more, making it a valuable tool for network administrators and IT professionals.
Usage:
sipcalc [OPTIONS]... <[ADDRESS]... [INTERFACE]... | [-]>Global options:
-a, --all: Display all possible information.-d, --resolve: Enable name resolution for addresses.-h, --help: Show help message and exit.-I, --addr-int=INT: Specify an interface to add.-n, --subnets=NUM: Display NUM extra subnets starting from the current subnet.-u, --split-verbose: Enable verbose output for subnet splitting.-v, --version: Show version information and exit.-4, --addr-ipv4=ADDR: Specify an IPv4 address to add.-6, --addr-ipv6=ADDR: Specify an IPv6 address to add.
IPv4 options:
-b, --cidr-bitmap: Show CIDR bitmap.-c, --classful-addr: Display classful address information.-i, --cidr-addr: Display CIDR address information (default).-s, --v4split=MASK: Split the current network into subnets of MASK size.-w, --wildcard: Display information for a wildcard (inverse mask).-x, --classful-bitmap: Show classful bitmap.
IPv6 options:
-e, --v4inv6: Show IPv4 compatible IPv6 information.-r, --v6rev: Generate IPv6 reverse DNS output.-S, --v6split=MASK: Split the current IPv6 network into subnets of MASK size.-t, --v6-standard: Show standard IPv6 address information (default).
Examples:
sipcalc -a 192.168.1.1/24
sipcalc -S 64 2001:db8::/32Address and netmask formats are flexible, supporting dotted quad, number of bits, and hex formats. The tool also supports reading arguments from stdin if - is used in place of an address or interface name.
For detailed usage and options, refer to the sipcalc manual or the help option -h.
snmpget
This is an SNMP application that uses the SNMP GET request to query for information on a network entity. One or more object identifiers (OIDs) may be given as arguments on the command line.
Synopsis
snmpget [OPTIONS] [-Cf] OID [OID]...Options
| Option | Description |
|---|---|
-h, --help | Display the help. |
-H | Display configuration file directives understood. |
-v 1|2c|3 | Specifies SNMP version to use. |
-V, --version | Display package version number. |
-Cf | If -Cf is not specified, some applications (snmpdelta, snmpget, snmpgetnext and snmpstatus) will try to fix errors returned by the agent that you were talking to and resend the request. The only time this is really useful is if you specified a OID that didn't exist in your request and you're using SNMPv1 which requires "all or nothing" kinds of requests. |
| other | For other options see the command help. |
Examples
Retrieve the variable system.sysDescr.0 from the host zeus using the community string public.
snmpget -c public zeus system.sysDescr.0snmpset
This is an SNMP application that uses the SNMP SET request to set information on a network entity. One or more object identifiers (OIDs) must be given as arguments on the command line. A type and a value to be set must accompany each object identifier.
Synopsis
snmpset [OPTIONS] OID TYPE VALUE [OID TYPE VALUE]...Options
| Option | Description |
|---|---|
-h, --help | Display the help. |
-H | Display configuration file directives understood. |
-v 1|2c|3 | Specifies SNMP version to use. |
-V, --version | Display package version number. |
| other | For other options see the command help. |
The TYPE is a single character, one of:
| Character | Description |
|---|---|
i | integer |
u | unsigned |
s | string |
x | hex string |
d | decimal string |
n | nullobj |
o | objid |
t | timeticks |
a | ipaddress |
b | bits |
Examples
Set the variables sysContact.0 and ipForwarding.0:
- system.sysContact.0 = STRING: "dpz@noc.rutgers.edu"
- ip.ipForwarding.0 = INTEGER: not-forwarding(2)
snmpset -c private -v 1 test-hub system.sysContact.0 s dpz@noc.rutgers.edu ip.ipforwarding.0 = 2snmptrap
Tips
See similar programs snmpinform and snmptrap.
This program can be used to send a SNMP trap.
Synopsis
snmptrap [-c <community>] [-g <generic>] [-s <specific>] <hostname> [<oid> <type> <value>]Options
| Option | Description |
|---|---|
-c | Community |
-g | Specifies generic trap types: • 0 — coldStart • 1 — warmStart • 2 — linkDown • 3 — linkUp • 4 — authenticationFailure • 5 — egpNeighborLoss • 6 — enterpriseSpecific |
-r | Sends MAC address of eth0 interface |
-s | Specifies user definition trap types in the enterpriseSpecific |
Examples
Send TRAP with info about the status of a digital input BIN0 to the IP address 192.168.1.2.
snmptrap 192.168.1.2 1.3.6.1.4.1.30140.2.3.1.0 u 'io get bin0'Send TRAP "warm start" to the IP address 192.168.1.2.
snmptrap -g 1 192.168.1.2ssh
This is a program for logging into a remote machine and for executing commands on a remote machine.
Synopsis
ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface] [-b bind_address]
[-c cipher_spec] [-D [bind_address:]port] [-E log_file]
[-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file]
[-J destination] [-L address] [-l login_name] [-m mac_spec]
[-O ctl_cmd] [-o option] [-P tag] [-p port] [-Q query_option]
[-R address] [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]
destination [command [argument ...]]Options
For more details see ssh(1) — Linux manual page.
| Option | Description |
|---|---|
-4 | Forces to use IPv4 addresses only. |
-6 | Forces to use IPv6 addresses only. |
-i identity_file | Specifies the file from which the identity (private key) for public key authentication is read. |
-l login_name | Specifies the user to log in as on the remote machine. |
-p port | Specifies the port to connect to on the remote host. |
-v | Verbose mode. Causes ssh to print debugging messages about its progress. This is helpful in diagnosing connection, authentication, and configuration problems. |
-A and -a | These options control the use of SSH agent forwarding, a mechanism for single sign-on. |
-X and -x | These manage X11 forwarding, enabling the secure transmission of X11 windows from the remote machine to the local machine. |
-L address | Specifies that connections to the given TCP port or Unix socket on the local (client) host are to be forwarded to the given host and port, or Unix socket, on the remote side. |
-C | Requests compression of all data. This can speed up transfers over slow networks. |
-F configfile | Specifies an alternative per-user configuration file. |
Examples
ssh root@192.168.1.1This command is used for a basic login to a remote machine using the root user account. Replace 192.168.1.1 with the actual address of the remote host.
ssh -p 2222 username@remote_hostIf the SSH server is listening on a non-standard port (other than the default port 22), the -p option allows you to specify the port to connect to.
ssh -i /path/to/private_key username@remote_hostIn this scenario, the -i option allows you to specify a private key to use for authentication, instead of the default key. This is particularly useful when multiple keys are used for different servers or accounts.
ssh username@remote_host 'command'Here, you can execute a single command on the remote server without entering into a full login shell. Replace command with the desired command. For example, ssh user@server 'ls -l /var/www' lists the contents of the specified directory on the remote server.
ssh -L local_port:remote_host:remote_port username@ssh_serverThis example sets up SSH port forwarding. It forwards connections to a local port to a specified port on a remote machine. It's commonly used to securely access a service on the remote server that isn't exposed to the public internet.
tc
The tc (traffic control) command in Linux is a powerful tool utilized for managing network bandwidth and handling Quality of Service (QoS). It allows administrators to control the flow of network traffic by defining policies for traffic classification, prioritization, and rate limiting, among other functionalities. This command is essential for optimizing network performance and ensuring that critical network services remain highly available and responsive.
Synopsis
tc [OPTIONS] OBJECT { COMMAND | help }Description
Tc operates on several objects such as qdiscs (queuing disciplines), classes, and filters, each of which plays a vital role in defining traffic control policies. By manipulating these objects, administrators can tailor the network traffic behavior to suit the specific needs of their environment. This includes creating traffic queues, setting up bandwidth limits for different types of traffic, and applying traffic filters to categorize network packets into various classes.
Options
Common options include:
-s: Show detailed information. When used, tc displays more detailed information about the specified object.-d: Show raw data. This option is useful for debugging purposes.-p: Pretty print. Formats the output in a more readable form.-b: Batch mode. Allows tc to read a series of commands from a file.
Examples
Show all current qdiscs:
tc -s qdisc showLimit the outbound traffic rate on an interface:
tc qdisc add dev eth0 root tbf rate 1mbit burst 32kbit latency 400msFor a comprehensive guide on setting up Quality of Service (QoS) with tc, refer to our Quality of Service (QoS) Application Note available at https://icr.advantech.com/download/application-notes#quality-service-qos.
tcpdump
This program can be used to dump traffic on a network.
Synopsis
tcpdump [-AdDeflLnNOpqRStuUvxX] [-c <count>] [-C <file size>] [-E algo:secret]
[-F <file>] [-i <interface>] [-r <file>] [-s <snaplen>] [-T type] [-w <file>]
[-y <datalinktype>] [expression]Options
For detailed description of this command, visit Linux manual pages.
Examples
View traffic on interface ppp0.
tcpdump -n -i ppp0View traffic on interface eth0 except protocol Telnet.
tcpdump -n not tcp port 23View UDP traffic on interface eth0.
tcpdump -n udpView HTTP traffic on interface eth0.
tcpdump -n tcp port 80View all traffic from/to IP address 192.168.1.2.
tcpdump -n host 192.168.1.2View traffic from/to IP address 192.168.1.2 except protocol Telnet.
tcpdump -n host 192.168.1.2 and not tcp port 23telnet
This program can be used to establish interactive communication with another computer over a network using the TELNET protocol.
Synopsis
telnet <host> [<port>]Examples
Connect to 192.168.1.2 by protocol Telnet.
telnet 192.168.1.2traceroute
This program can be used to track the route to a network host.
Synopsis
traceroute [-FIldnrv] [-f <1st_ttl>] [-m <max_ttl>] [-p <port#>] [-q <nqueries>]
[-s <src_addr>] [-t <tos>] [-w <wait>] [-g <gateway>] [-i <iface>] [-z <pausemsecs>]
host [data size]Options
| Option | Description |
|---|---|
-4,-6 | Force IP or IPv6 name resolution |
-F | Set the don't fragment bit |
-l | Display the TTL value of the returned packet |
-n | Print hop addresses numerically rather than symbolically |
-r | Bypass the normal routing tables and send directly to a host |
-f N | First number of hops (default 1) |
-m N | Set the max time-to-live (max number of hops) |
-q N | Set the number of probes per hop (default is 3) |
-p N | Set the base UDP port number used in probes (default is 33434) |
-s IP | Use the following IP address as the source address |
-i IFACE | Source interface |
-t N | Set the type-of-service in probe packets to the following value (default 0) |
-w SEC | Set the time (in seconds) to wait for a response to a probe (default 3 sec) |
-z MSEC | Wait before each send |
-I | Use ICMP ECHO instead of UDP datagrams |
-d | Enable socket level debugging |
-v | Verbose output |
Examples
Trace the route to a host:
traceroute 8.8.8.8Trace without DNS resolution:
traceroute -n 8.8.8.8Trace using ICMP ECHO packets:
traceroute -I 8.8.8.8Limit the maximum number of hops to 15:
traceroute -m 15 8.8.8.8Use a specific source interface and send only 1 probe per hop:
traceroute -i eth0 -q 1 8.8.8.8traceroute6
This command is a network diagnostic tool included with BusyBox that is designed to trace the path packets take to reach an IPv6 host. By sending packets with incrementally increasing hop limits (TTL, Time-To-Live), traceroute6 determines the route packets follow to reach the target host. This command is essential for identifying network bottlenecks and routing issues in IPv6 networks.
Synopsis
traceroute6 [-nrv] [-f 1ST_TTL] [-m MAXTTL] [-q PROBES] [-p PORT]
[-t TOS] [-w WAIT_SEC] [-s SRC_IP] [-i IFACE] [-z PAUSE_MSEC] HOST [BYTES]Descriptiontraceroute6 utilizes IPv6 packets to trace the network route from the source to the specified HOST. It provides various options to customize the trace, including setting the first and maximum number of hops, the number of probes per hop, and the source IP address or interface.
Options
-n: Do not resolve IP addresses to their domain names, display numeric addresses.-r: Bypass the normal routing tables and send directly to the host.-f N: Set the initial time-to-live (hop limit) to N.-m N: Specify the maximum number of hops (TTL) traceroute6 will probe.-q N: Set the number of probe packets per hop.-p N: Use N as the base UDP port number for probes.-s IP: Use IP as the source address for the outgoing probe packets.-i IFACE: Specify the interface through which traceroute should send packets.-t N: Set the type-of-service in probe packets to N.-w SEC: Set the time to wait for a response to a probe.-z MSEC: Wait MSEC milliseconds between sending each packet.
Examples
Trace the route to an IPv6 host without resolving names:
traceroute6 -n HOSTTrace the route with a specific number of probes per hop:
traceroute6 -q 1 HOSTSpecify a source address and maximum number of hops:
traceroute6 -s SRC_IP -m 15 HOSTtraceroute6 offers valuable insights into the network path and performance characteristics between the source and an IPv6 destination, aiding in network troubleshooting and analysis.
vconfig
This program can be used to create and remove virtual ethernet devices.
Synopsis
vconfig command [OPTIONS]Options
| Command [OPTIONS] | Description |
|---|---|
add IFACE VLAN_ID | Creates a vlan-device on IFACE. The resulting vlan-device will be called according to the nameing convention set. |
rem VLAN_NAME | Removes the named VLAN_NAME. |
set_flag IFACE 0|1 VLAN_QOS | When 1, ethernet header reorders are turned on. Dumping the device will appear as a common ethernet device without vlans. When 0(default) however, ethernet headers are not reordered, which results in vlan tagged packets when dumping the device. Usually the default gives no problems, but some packet filtering programs might have problems with it. |
set_egress_map VLAN_NAME SKB_PRIO VLAN_QOS | This flags that outbound packets with a particular skb-priority should be tagged with the particular vlan priority vlan-qos. The default vlan priority is 0. |
set_ingress_map VLAN_NAME SKB_PRIO VLAN_QOS | This flags that inbound packets with the particular vlan priority vlan-qos should be queued with a particular skb-priority. The default skb-priority is 0. |
set_name_type NAME_TYPE | Sets the way vlan-device names are created. Use vconfig without arguments to see the different formats. |
Tips
Vlan ID 4091 and 4092 are reserved for the system
Examples
Create VLAN ID 1 on eth0 Ethernet interface.
vconfig add eth0 1wget
The wget utility is a non-interactive network downloader used to retrieve files from the web using HTTP, HTTPS, or FTP protocols. Because it is non-interactive, it is highly suitable for use in background scripts, cron jobs, or automated provisioning.
Synopsis
wget [options] <URL>Options
| Option | Description |
|---|---|
--spider | Only check URL existence: $? is 0 if exists |
-c | Continue retrieval of aborted transfers |
-q | Quiet mode — do not print |
-P DIR | Save to DIR (default .) |
-S | Show server response |
-T SEC | Network read timeout is SEC seconds |
-O FILE | Save to filename ('-' for stdout) |
-o FILE | Log messages to FILE |
-U STR | Use STR for User-Agent header |
-Y on/off | Use proxy ('on' or 'off') |
Examples
Download a file from an HTTP server:
wget http://10.0.0.1/my.cfgSave a downloaded file under a different name:
wget -O /tmp/new_config.cfg http://10.0.0.1/my.cfgCheck whether a file exists without downloading:
wget --spider http://10.0.0.1/my.cfgScripting/Shell Commands
This section covers commands integral to shell scripting and command-line manipulation. These commands are foundational for automating tasks, managing files, and configuring system behavior through scripts.
awk
This program scans each input file for lines that match any of a set of patterns specified literally in program-text or in one or more files specified as -f progfile.
Synopsis:
awk [-v var=val] [-F FS] [-f progfile] [<program-text>] [<file> ...]Options:
| Option | Description |
|---|---|
-v | Assign the value val to the variable var, before execution of the program begins. Such variable values are available to the BEGIN block of an AWK program. |
-F | Use for the input field separator (the value of the FS predefined variable). |
-f | Read the AWK program source from the file program-file, instead of from the first command line argument. Multiple -f (or --file) options may be used. |
Examples:
Show IP address of Gateway:
route -n | awk '/^0.0.0.0/ { print $2 }'break
This command is used within looping constructs in Bash/Shell scripting to exit from the loop prematurely. It breaks out of the nearest enclosing loop, skipping the remaining iterations of the loop.
Synopsis:
break [n]The optional argument n specifies how many enclosing loops to break out of (default: 1).
clear
This command clears the terminal screen, moving the cursor to the home position (top-left corner). It is equivalent to pressing Ctrl+L in most terminals. The screen content is not deleted from memory — only the display is refreshed.
Synopsis:
clearcontinue
The continue command is used within loops in Bash/Shell scripting to skip the rest of the current loop iteration and continue with the next iteration. This command is particularly useful when a condition is met that requires prematurely proceeding to the next cycle of the loop without executing the remaining commands in the current iteration.
Synopsis:
continue [n]The optional argument n specifies how many levels of enclosing loops to skip (default: 1).
echo
This command prints the strings to standard output.
Synopsis:
echo [-n] [-e] [-E] [<string> ...]Options:
| Option | Description |
|---|---|
-n | Do not output the trailing newline. |
-e | Enable interpretation of backslash escapes. |
-E | Disable interpretation of backslash escapes (default). |
Examples:
Switch profile to "Standard":
echo "PROFILE=" > /etc/settings
rebootSwitch profile to "Alternative 1":
echo "PROFILE=alt1" > /etc/settings
rebootSend a sequence of bytes 0x41,0x54,0x0D,0x0A to serial line (write data in octal):
echo -n -e "\\101\\124\\015\\012" > /dev/ttyS0eval
This command is a built-in utility in Bash/Shell scripting environments used to concatenate its arguments into a single command, which is then executed by the shell. This command is particularly useful for constructing commands based on variables or processing complex expressions where commands depend on other commands' outputs or file contents.
Synopsis:
eval [arg ...]Examples:
Execute a dynamically constructed command:
CMD="echo Hello"
eval $CMDParse output from a previous command:
eval $(ipcalc -p 192.168.1.100/24)
echo $PREFIXCreate a function from variable content:
FUNC='greet() { echo "Hello, $1!"; }'
eval "$FUNC"
greet Worldexec
This command is used in shell scripting to replace the current shell process with a specified program. Unlike running a program normally, exec does not return to the shell once the program completes. Instead, the new program takes over the current process space, maintaining the same process ID (PID).
Synopsis:
exec command [arguments]Examples:
Replace the shell with the vi editor:
exec vi /etc/settings.pppRedirect all output of the script to a log file:
exec > /tmp/script.log 2>&1
echo "This goes to the log"exit
This command terminates the current shell session or script execution. It allows the script or shell to exit with an optional exit status, which can be used to indicate the success or failure of the script's execution to the calling environment.
Synopsis:
exit [n]The exit status n is a value between 0 and 255 (0 = success).
Examples:
Exit successfully:
exit 0Exit with an error:
exit 1Show the exit status of the last command:
false; echo $?; exitexport
This command in shell scripting is utilized to set or export environment variables and functions to the current shell and all processes started from it. By marking an environment variable or function to be exported, it becomes available to subprocesses spawned from the shell, allowing those processes to use the variable or function. This command is integral for configuring the shell environment dynamically.
Synopsis:
export [NAME[='VALUE'] ...]Description:
Without arguments, export displays a list of all names that are exported in the shell session. When accompanied by NAME or NAME='VALUE', the command sets the environment variable NAME to VALUE, or exports the NAME if VALUE is omitted. This enables configurations like setting the PATH, defining the home directory, and configuring terminal settings to be inherited by child processes.
Examples:
Set the HOME environment variable:
export HOME='/root'Export the PATH environment variable, appending a new directory:
export PATH=$PATH:/usr/local/binDisplay exported names:
exportList all exported names in portable format:
export -pRemove a variable from the exported list:
export -n MYVARhash
This command in shell scripting is utilized to handle the hash table of commands in memory, which tracks the full path of previously executed commands. This optimizes the shell's performance by avoiding the need to search the $PATH environment variable for command locations on subsequent executions.
Synopsis:
hash [options] [name ...]Description:
When called without arguments, hash displays the contents of the hash table, including command names and their associated full paths. Specifying one or more names as arguments adds those commands to the hash table, assuming they can be found in the directories listed in the $PATH environment variable. This command is particularly useful in scripts and sessions where certain commands are executed repeatedly, reducing overall command lookup times.
Options:
-r: Resets the hash table, clearing all remembered locations.-l: Displays output in a format that is reusable as shell input.-p pathname name: Defines a pathname for a command name, bypassing$PATHsearch and hash table lookup.-d name: Removes the specified name from the hash table.-t name: Displays the remembered location of the specified command, without altering the hash table.
Examples:
Display the hash table:
hashAdd a command to the hash table:
hash myscriptReset the hash table:
hash -rSpecify a pathname for a command:
hash -p /usr/local/bin/myscript myscriptRemove a command from the hash table:
hash -d myscriptinc
This command is a specialized, proprietary tool designed to output a number that is incremented by one from the given value. This utility can be particularly useful in scripting and automation tasks where numerical adjustments and calculations are required.
Synopsis:
inc <value>Description:
Accepting a numerical value as input, the inc command calculates and displays the value increased by one. This command simplifies operations that involve numerical incrementation, streamlining the process of generating sequences or adjusting values dynamically in scripts.
Examples:
Increment a given value:
inc 5Output: 6
Use in an arithmetic sequence:
val=10; next=$(inc $val); echo $nextOutput: 11
Increment a variable step by step:
x=20; x=$(inc $x); echo $xOutput: 21
let
This command in Linux is a built-in shell command primarily used for evaluating arithmetic expressions. It provides a straightforward method for performing numerical calculations, supporting a wide range of operators similar to those found in traditional programming languages. This command allows for direct manipulation and evaluation of shell variables and expressions within scripts.
Synopsis:
let "expression"Description:
let evaluates each expression argument as an arithmetic expression. Variable names in expressions refer directly to shell variables without needing a dollar sign prefix. Arithmetic expansions performed by let allow assignment, various arithmetic operations, conditional expressions, and even bitwise operations, making it versatile for scripting applications where numerical computation is required.
Examples:
Increment a variable:
count=5
let "count += 1"
echo $count # Outputs: 6Perform arithmetic with variables:
a=10
b=3
let "c = a * b"
echo $c # Outputs: 30Use conditional expressions:
x=15; y=25
let "z = (x > y) ? x : y"
echo $z # Outputs: 25local
This command is a shell built-in that is used within functions to declare variables as having a function-local scope. It prevents variable names from conflicting with variables outside the function, making shell scripts more reliable and modular.
Synopsis:
local [name[=value] ...]Examples:
Use local variables inside a function:
greet() {
local name="$1"
echo "Hello, $name!"
}
greet World
echo $name # Empty — $name is local to greet()nohup
nohup is short for “No Hang-up”. Nohup is a supplemental command that tells the system not to stop another command once it has started. That means it’ll keep running until it’s done, even if the user that started it logs out.
Synopsis:
nohup <program> [<arguments>]Options:
| Option | Description |
|---|---|
program | Program to be run immune to hang-ups with output to a non-tty. |
arguments | Arguments for the program. |
Examples:
Run ping in background, immune to logout:
nohup ping -c 10 google.com &Output:
nohup: appending output to nohup.outRedirect nohup output to a custom log file:
nohup ./myscript.sh > mylog.txt 2>&1 &printf
This command formats and prints ARGUMENT(s) according to FORMAT, where FORMAT controls the output exactly as in C printf. For detailed information please see documentation for C programming language.
Synopsis:
printf FORMAT [ARGUMENT...]Format options:
| Option | Description |
|---|---|
d or i | Signed decimal integer |
u | Unsigned decimal integer |
o | Unsigned octal |
x | Unsigned hexadecimal integer |
X | Unsigned hexadecimal integer (uppercase) |
f | Decimal floating point, lowercase |
e | Scientific notation (mantissa/exponent), lowercase |
E | Scientific notation (mantissa/exponent), uppercase |
g | Use the shortest representation: %e or %f |
G | Use the shortest representation: %E or %F |
a | Hexadecimal floating point, lowercase |
A | Hexadecimal floating point, uppercase |
c | Character |
s | String of characters |
p | Pointer address |
n | Store the number of characters printed so far |
% | A % followed by another % character will write a single % to the stream. |
Examples:
Print number 10 in unsigned hexadecimal integer (uppercase) format:
printf "Output: %X \n" 10
# Output: AExample of printing system variables:
printf "User '%s' in directory '%s'.\n" "$USER" "$PWD"
# User 'root' in directory '/home/httpd'.Right-aligned decimal:
printf "Value: %8d\n" 42
# Value: 42read
This command in shell scripting is utilized to read a line of input from standard input (stdin) or a file descriptor. It is frequently employed in scripts to capture user input or to process text files or streams line by line.
Synopsis:
read [-r] [-t TIMEOUT] [-p PROMPT] [VARIABLE ...]Options:
| Option | Description |
|---|---|
-r | Raw mode — do not interpret backslash escapes. |
-t TIMEOUT | Time out and return failure if no input is received within TIMEOUT seconds. |
-p PROMPT | Display PROMPT on stderr before reading. |
Examples:
Read into a single variable:
read NAME
echo "Hello, $NAME"Read into multiple variables:
read FIRST LAST
echo "$LAST, $FIRST"Read with a timeout:
read -t 5 -p "Enter value: " VAL || echo "Timed out"readonly
This command in shell scripting is used to mark variables and functions as immutable. Once a variable or a function is set to read-only, its value or function body cannot be changed or unset. Attempting to modify a read-only variable or function will result in an error.
Synopsis:
readonly [-p] [name[=value] ...]Examples:
Declare a read-only variable:
readonly VERSION="1.0"
VERSION="2.0" # Error: VERSION: is read onlyreturn
This command is utilized within shell functions to terminate the function execution and optionally return an exit status to the calling environment. This command is similar in behavior to the exit command but is specifically designed for use within functions.
Synopsis:
return [n]Examples:
Return success from a function:
check_file() {
[ -f "$1" ] && return 0 || return 1
}
check_file /etc/settings && echo "Found" || echo "Not found"shlock
This command is a proprietary utility designed to lock a specified file during the execution of a script. This mechanism ensures that the file is not accessed or modified by other processes until the script completes its execution. If the file is already locked, shlock will wait until the lock is released before proceeding.
Synopsis:
shlock <filename>Description:
Upon invocation, shlock attempts to create a lock on the specified file, preventing other instances or processes from modifying the file concurrently. This command is particularly useful in scripts that perform critical operations on files, requiring exclusive access to prevent data corruption or loss. If a lock cannot be immediately acquired due to an existing lock on the file, shlock enters a wait state until the lock becomes available.
Examples:
Lock a file for exclusive script access:
shlock /path/to/myfileset
This command is a shell built-in that sets or unsets shell options and positional parameters. It can modify the operational behavior of the shell, set positional parameters to the script, and enable or disable shell features.
Synopsis:
set [--] [arg1 arg2 ...]
set -e | -x | +e | +xExamples:
Enable immediate exit on error:
set -eEnable command tracing (print each command before executing):
set -xshift
This command in shell scripting is used to shift the positional parameters to the left by a specified number of positions, which effectively decreases the number of positional parameters. This is particularly useful in scripts that process an arbitrary number of arguments in a loop.
Synopsis:
shift [n]Examples:
Process all script arguments one by one:
while [ $# -gt 0 ]; do
echo "Arg: $1"
shift
doneShift by 2 positions:
set -- a b c d e
shift 2
echo $1 # Outputs: csleep
This program can be used to delay for a specified amount of time.
Synopsis:
sleep <time>Examples:
Sleep for 30 seconds:
sleep 30Sleep for 5 minutes:
sleep 300Wait for internet connectivity every 10 seconds:
while ! ping -c 1 8.8.8.8 > /dev/null 2>&1; do
sleep 10
done
echo "Connected"source
This command in Unix-like operating systems is a shell built-in command used to read and execute commands from a specified file in the current shell environment. This command is commonly used to apply configuration changes, set environment variables, or define functions without starting a new shell session. The source command ensures that any variables or functions declared in the file are available in the current shell session.
Synopsis:
source filename [arguments]Description:
The source command reads and executes commands from the given filename argument in the current shell context. If the specified file contains export statements, function definitions, or variable assignments, they will be applied to the running shell session, affecting its behavior. This command is particularly useful for scripts and configuration files that need to modify the environment of the current shell. Arguments can be passed to the sourced script, which then access them as positional parameters.
Examples:
Load system-wide environment variables:
source /etc/profileSource a configuration script so its variables remain in the current shell:
# Running a script normally creates a subshell — variables are lost:
sh /etc/myconfig.sh # Variables NOT available here
# Sourcing keeps variables in the current shell:
source /etc/myconfig.sh # Variables ARE available heretest
This command in Linux is a fundamental tool utilized for evaluating conditional expressions. It allows scripts and users to check file types, compare values, and perform logical operations, serving as the backbone for conditional statements in shell scripting. This command facilitates decision-making processes in scripts by testing expressions and returning an exit status based on the evaluation result.
Synopsis:
test EXPRESSION
[ EXPRESSION ]Description:
The test command evaluates the EXPRESSION provided as an argument. If the EXPRESSION evaluates to true, test returns an exit status of 0 (success). If the EXPRESSION evaluates to false, it returns a non-zero exit status (failure). This behavior integrates seamlessly with the if statements in shell scripts, enabling conditional execution of commands.
Commonly Used Tests:
-e FILE: Returns true ifFILEexists (regardless of type).-f FILE: Returns true ifFILEexists and is a regular file.-d DIRECTORY: Returns true ifDIRECTORYexists and is a directory.-z STRING: Returns true ifSTRINGis empty.-n STRING: Returns true ifSTRINGis not empty.STRING1 = STRING2: Returns true if the strings are equal.STRING1 != STRING2: Returns true if the strings are not equal.-eq, -ne, -lt, -le, -gt, -ge: Numerical comparisons between integers.
Examples:
Check if a file exists:
test -f /path/to/file && echo "File exists." || echo "File does not exist."Compare two strings:
test "string1" = "string2" && echo "Equal" || echo "Not equal"Check if a variable is set:
test -n "$VARIABLE" && echo "Variable is set" || echo "Variable is not set"trap
This command in Unix-like operating systems is a shell builtin that allows scripts to execute a command or a set of commands when receiving specified signals. This functionality is crucial for ensuring that scripts can handle unexpected events gracefully, perform cleanup operations, or take specific actions when interrupted.
Synopsis:
trap [COMMANDS] [SIGNALS]Description:
trap enables the specification of commands (COMMANDS) to be executed automatically in response to various signals (SIGNALS). Signals are operating system messages that communicate to processes about events like termination requests, keyboard interrupts, or other conditions that require attention. By default, certain signals cause a script to terminate, but with trap, scripts can respond in user-defined ways, allowing for more robust and reliable behavior.
Common Signals:
SIGINT: Interrupt signal, typically sent by pressingCtrl+C.SIGTERM: Termination signal, requesting the program to end gracefully.SIGHUP: Hangup signal, often sent when a terminal window is closed.EXIT (0): A pseudo-signal used to execute commands when the shell exits (regardless of the reason).
Examples:
Trap an interrupt signal and execute a cleanup function:
trap cleanup_function SIGINTRemove temporary files upon script exit:
trap 'rm -f /tmp/mytempfile' EXITReset trap to default behavior for SIGINT:
trap - SIGINTtype
This command is a shell builtin that displays the kind of command the shell will execute, given a command name as an argument. This includes identifying whether the command is a shell builtin, an alias, a function, a keyword, or an external file. The type command is an essential tool for debugging and scripting, as it clarifies command resolution and helps script authors understand how their commands will be interpreted by the shell.
Synopsis:
type <command_name>Examples:
Check if cd is a builtin:
type cd
# cd is a shell builtinCheck the location of cat:
type cat
# cat is /bin/catVerify that a required program is installed before using it:
type wget || { echo "wget not found"; exit 1; }unset
This command in shell scripting is used to remove variables or functions from the shell environment. By unsetting a variable or function, you effectively delete it, making its value or definition no longer accessible in the current session. This command is particularly useful in scripting to ensure that the environment is clean or to prevent accidental reuse of variables and functions with stale data.
Synopsis:
unset [-v] [-f] <name>Examples:
Unset a variable:
MYVAR="hello"
unset MYVAR
echo $MYVAR # Emptywait
This command in Unix-like operating systems is a shell builtin that suspends the execution of the shell script until processes identified by their Process ID (PID) have terminated or until a specified job number has completed. It is primarily used in scripts to halt script progress until background processes or jobs have finished executing, making it essential for scripts that rely on the completion of parallel processes.
Synopsis:
wait [PID]Examples:
Start two background processes and wait for both:
sleep 5 &
PID1=$!
sleep 3 &
PID2=$!
wait $PID1
wait $PID2
echo "Both done"Wait for all background jobs to complete:
for i in 1 2 3; do
sleep $i &
done
wait
echo "All background jobs finished"watch
This program periodically runs a command and displays its output, refreshing the screen each time.
Synopsis:
watch [-n SEC] [-t] <command>Options:
| Option | Description |
|---|---|
-n SEC | Specify the update interval in seconds (default: 2). |
-t | Turn off the header showing the command and timestamp. |
Examples:
Watch the system log update every 2 seconds:
watch -n 2 slogMonitor network interfaces without the header:
watch -t -n 1 ifconfig eth0xargs
This program executes the command on every item given by standard input.
Synopsis:xargs [<commands>] [<options>] [<args> ...]
Options:
| Option | Description |
|---|---|
-o | Open /dev/tty for the program's stdin |
-n <n> | Pass at most n arguments per command invocation |
-s <n> | Limit the command line length to n bytes |
-E <str> | Stop processing at the line matching str |
-e[<str>] | Same as -E, but the string is optional |
-r | Do not run command for empty input lines |
-t | Print the command line on stderr before executing it |
Examples:
Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces.
find /tmp -name core -type f -print | xargs /bin/rm -fLimit arguments per command:
printf "1 2 3 4 5 6" | xargs -n 2 echo "Pair:"
# Pair: 1 2
# Pair: 3 4
# Pair: 5 6