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.
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 onPower off the CDMA module:
cdmapwr offesim
💡 This command is available only on selected devices, depending on the cellular module used, and is intended for use in customer project deployments.
This command manages eSIM profiles on the eUICC of the cellular module. It can list the installed profiles, download a new profile, and delete, enable, or disable an existing profile.
Synopsis:
esim [-h] [-i] list | download <actcode> [<confcode>] | delete <iccid> | enable <iccid> | disable <iccid> | notifyCommands:
| Command | Description |
|---|---|
list | List the eSIM profiles installed on the eUICC, including their status, ICCID, and provider. |
download <actcode> [<confcode>] | Download a new eSIM profile from the operator's SM-DP+ server using the activation code. Some operators also require a confirmation code. |
delete <iccid> | Delete the profile with the specified ICCID. |
enable <iccid> | Enable the profile with the specified ICCID. |
disable <iccid> | Disable the profile with the specified ICCID. |
notify | Send pending profile management notifications (install, enable, disable, and delete events) to the operator's SM-DP+ server. |
Warning
Do not call disable on the eSIM profile the router is currently using for mobile communication. If Mobile WAN is actively connected through this profile, first disable the mobile connection (uncheck it on the Configuration → Mobile WAN page) or switch to a different SIM, and only then disable the profile.
Options:
| Option | Description |
|---|---|
-h | Format the output as HTML. |
-i | Insecure mode — do not verify the HTTPS certificate of the SM-DP+ server. |
Examples:
List the installed eSIM profiles:
esim listEnable the profile with the given ICCID:
esim enable 89440000000000000000gsminfo
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.
halt
This command shuts down the router so it can be safely powered off. It properly stops all running services, turns off the PWR LED, and then waits for 100 seconds, during which the router can be safely unplugged from the power supply. If the router remains powered after this period, it reboots automatically.
Synopsis:
haltExample:
Shut down the router for safe power-off:
halthwclock
This command queries and sets 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 command reads binary inputs and controls binary outputs of the router. If an expansion board is installed, it also supports the router's expansion ports.
Synopsis:
io [get <pin>] | [set <pin> <value>]Options:
| Option | Description |
|---|---|
get | Get the state of the specified input pin. |
set | Set the state of the specified output pin. |
Examples:
Get the state of digital input BIN0:
io get bin0Get the state of analog input AN1 on expansion port XC-CNT:
io get an1Get the state of counter input CNT1 on expansion port XC-CNT:
io get cnt1Set 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 onStart blinking slowly with the USR LED:
led slowControl 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 command switches the router into Low Power Mode (LPM) to minimize power consumption. The router can be woken from this state by one of two events: the expiration of a specified time interval or a signal change on a binary input. If both wake-up conditions are configured, the router wakes up as soon as the first event occurs.
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. The interval represents the duration of the actual low power sleep only; it does not include the time required for system shutdown and startup. |
Examples:
Sleep the router for five minutes:
lpm -i 300Sleep the router and wake up by activating the digital input:
lpm -bSleep the router for five minutes or less if the digital input is activated within five minutes:
lpm -b -i 300mac
This command displays the MAC address of the eth0 interface.
Synopsis:
mac [<separator>]Examples:
Display the MAC address of eth0 using '-' as the separator instead of the default ':':
mac -port1
This command controls the first expansion port.
Synopsis:
port1 [on|off|auto|rs232|rs485|type]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. |
type | Display the type of the expansion board installed (e.g., RS-232 or RS-485). |
Examples:
Enable the first expansion port in RS485 mode:
port1 rs485Disable the first expansion port:
port1 offShow the type of the installed expansion board:
port1 typeport2
This command controls the second expansion port.
Synopsis:
port2 [on|off|auto|rs232|rs485|type]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. |
type | Display the type of the expansion board installed (e.g., RS-232 or RS-485). |
Examples:
Enable the second expansion port in RS232 mode:
port2 rs232Disable the second expansion port:
port2 offShow the type of the installed expansion board:
port2 typeportd
This program facilitates the transparent transfer of data between a serial line and a network using TCP or UDP protocols. It can operate in two primary modes: as a server that waits for incoming connections, or as a client that connects to a specified host.
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 <device> | Specifies the serial line device path, e.g., /dev/ttyS0. This option is mandatory. |
-b <baudrate> | Sets the communication speed in bits per second (baud rate). Default is 9600. |
-d <databits> | Sets the number of data bits. Valid values are 5, 6, 7, or 8. Default is 8. |
-p <parity> | Sets the parity. Use N for None, E for Even, or O for Odd. Default is None. |
-s <stopbits> | Sets the number of stop bits. Valid values are 1 or 2. Default is 1. |
-l <split timeout> | Sets the timeout in milliseconds for data packetization. If the time between consecutive characters received from the serial port exceeds this value, the buffered data is sent as a single network packet. Default is 20 ms. |
-4 | Forces RS485 mode. This typically involves managing the RTS signal for controlling the line driver. |
-h <hostname> | Specifies the hostname or IP address of the remote server to connect to. When this option is used, portd operates in client mode. If omitted, it runs in server mode, listening for incoming connections. |
-o <proto> | Sets the communication protocol. Specify tcp or udp. Default is TCP. |
-t <port> | Specifies the TCP or UDP port number to listen on (server mode) or connect to (client mode). This option is mandatory. |
-k <time> | Sets the TCP keepalive time in seconds. This is the duration of inactivity before the first keepalive probe is sent. A value of 0 disables keepalive. |
-i <interval> | Sets the interval in seconds between individual TCP keepalive probes. Default is 10 seconds. |
-r <probes> | Sets the number of unacknowledged TCP keepalive probes to send before considering the connection to be dead. Default is 5 probes. |
-x | Use Carrier Detect (CD) signal to indicate TCP connection status. The router's DTR pin is asserted (high) when a TCP connection is active and de-asserted (low) when disconnected. This can be used to signal connection status to an attached device. |
-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 (e.g., after binding to a privileged port). |
-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 client establishes a TCP connection, the program transparently transfers data from the serial port /dev/ttyS0, which is configured for 115200 bit/s, 8 data bits, no parity, and 1 stop bit (8N1). The process runs in the background:
portd -c /dev/ttyS0 -b 115200 -t 1000 &Run as a TCP client connecting to a server at IP address 192.168.1.100 on port 2000. Data from the local serial port /dev/ttyS1 (at 9600, 8N1) is forwarded to the remote server. The connection has TCP keepalive enabled with a 60-second idle time:
portd -c /dev/ttyS1 -b 9600 -h 192.168.1.100 -t 2000 -k 60 &pse
💡 This program is only supported on models supporting the PoE PSE functionality.
This command enables or disables the PoE PSE feature on the 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 the specified interface (port). |
off | Disable the PoE PSE on the specified interface (port). |
Examples:
Enable the PoE PSE on eth1 Ethernet interface:
pse eth1 onEnable the PoE PSE on lan2 port of Ethernet switch interface:
pse lan2 onreboot
This command reboots the router. Before restarting, it properly shuts down all running services.
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 a diagnostic report for the router.
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 a report including the configuration section:
report -aGenerate only the status and log sections:
report -s -lsms
This command sends an SMS message from the router's cellular module.
Synopsis:
sms <phone_number> "<text>"Arguments:
| Argument | Description |
|---|---|
<phone_number> | The recipient's telephone number. It is recommended to use the international format (e.g., +420123456789). |
<text> | The content of the SMS message. The text must be enclosed in double quotes if it contains spaces or special characters. |
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 | usb | 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 / sim 1 | Reports daily statistics for the first SIM card, including data usage (RX/TX), connection count, signal history, cell changes, and network availability. status sim is an alias for status sim 1. |
sim 2 | Reports the same daily statistics as above, but for the second SIM card. |
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 the router's peripheral ports — the type of the expansion ports (e.g., RS-232, RS-485), the state of the digital inputs and outputs, and the USB port status (on models equipped with a USB port). |
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 of the router, including the presence of wireless modules (Mobile WAN, GNSS, Wi-Fi, Bluetooth) and eSIM support, the number of serial ports, digital inputs and outputs, and USB ports, PoE capabilities (PD/PSE), and the product's designated region. |
usb | Displays detailed information about connected USB devices (manufacturer, product, vendor/product ID, class, USB version, speed, and driver), on models equipped with a USB port. |
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 sysExample output:
Part Number : ICR-3211B
Firmware Version : 6.6.0 (2025-12-17)
Serial Number : ACZ1100000011434
Product Revision : N/A
Profile : Standard
Free Space : 696.6 MiB for apps, 450.2 MiB for data
RTC Battery : Ok
Supply Voltage : 23.8 V
Temperature : 37 °C
Time : 2026-04-13 11:48:30
Uptime : 112 days, 16 hours, 49 minutesShow the status of the peripheral ports:
status portsExample output:
Expansion Port 1 : RS-232
Expansion Port 2 : RS-485
Digital Input : On
Digital Output : Off
USB Port : disabledShow hardware feature information:
status hwExample output:
Mobile WAN : 1
eSIM : 0
GNSS : 0
WiFi : 1
Bluetooth : 0
Serial Ports : 2
PoE PD : 0
PoE PSE : 0
Digital Inputs : 1
Digital Outputs : 1
USB Ports : 1
Region : Outside North Americastty
This command prints or changes terminal line settings.
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 manual for your router model or directly in the router console, as described below.
This command provides tools for working 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 also function as a watchdog for user processes.
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 strips the directory path and an optional suffix from a filename.
Synopsis:basename FILE [SUFFIX]
Examples:
Strip the directory from the path /home/myfile.txt:
basename /home/myfile.txtOutput:
myfile.txtStrip the directory and the .txt extension from the path /home/myfile.txt:
basename /home/myfile.txt .txtOutput:
myfilecat
This command concatenates files and prints to standard output.
Synopsis:cat [<file>] ...
Options:
This command does not support any options.
Examples:
View the contents of the file /proc/tty/driver/atmel_serial (serial port information on v2i routers):
cat /proc/tty/driver/atmel_serialOutput:
serinfo:1.0 driver revision:
0: uart:ATMEL_SERIAL mmio:0xF8028200 irq:38 tx:0 rx:0 DSR|CD|RI
1: uart:ATMEL_SERIAL mmio:0xF0004200 irq:37 tx:0 rx:0 DSR|CD|RI
5: uart:ATMEL_SERIAL mmio:0xFFFFF200 irq:36 tx:0 rx:0 CTS|DSR|CD|RIMerge all router configuration files into a single file /tmp/my.cfg:
cat /etc/settings.* > /tmp/my.cfgcd
This command changes 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 is an alias for cd. See cd for full documentation.
cmp
The cmp utility compares two files of any type and writes the results to the standard output.
Synopsis:cmp [-l] [-s] [-n <num>] <file1> [<file2>]
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. |
-n <num> | Compare at most <num> bytes. |
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.
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 copies 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 first field of each line, using tab as the field separator:
cut -f1 file.txtDisplay the second field of each line, using colon as the field separator:
echo a:b | cut -d: -f2Output:
bDisplay the second and all subsequent fields:
echo a b c d | cut -d" " -f2-Output:
b c dDisplay the third and fourth characters:
echo abcd | cut -c3,4Output:
cddd
This command copies a file and optionally converts the data format according to the specified operands.
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 decodes Base64-encoded values. The decoded result is printed to standard output.
Synopsis:decode <base64>
Description:
The decode command takes a single Base64-encoded string as its argument and prints the decoded value. This is particularly useful for reading encoded values from configuration files.
Examples:
Decode a Base64-encoded string:
decode SGVsbG8sIFdvcmxkIQ==Output:
Hello, World!dirname
This command strips the non-directory suffix from a filename.
Synopsis:dirname FILENAME
Examples:
Strip the filename from the path /home/MyFolder/myfile.txt:
dirname /home/MyFolder/myfile.txtOutput:
/home/MyFolderfind
This command searches for files in a directory hierarchy.
Synopsis:find [<path> ...] [<expression>]
Options:
The default path is the current directory and the default expression is -print. 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 24 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. It is an essential tool for parsing logs and filtering command outputs.
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 command decompresses a file. If the filename is -, data is read from standard input.
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 command compresses a file using 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.
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:
echo '{"foo": 0, "bar": 1}' | jq '.bar'Output:
1Apply a filter to each element in a JSON array:
echo '[{"foo": 0}, {"foo": 1}]' | jq '.[] | .foo'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 [-EFIN~] [file] ...Options
| Option | Description |
|---|---|
-E | Quit once the end of a file is reached. |
-F | Quit if the entire file fits on the first screen. |
-I | Ignore case in all searches. |
-N | Prefix a line number to each line. |
-~ | Suppress the ~ characters displayed past the end of the file. |
Examples
Display the contents of file.txt, allowing navigation through the file.
less file.txtDisplay file.txt with line numbers.
less -N file.txtOpen log.txt in less, quitting once the whole file fits on the first screen.
less -F log.txtln
This command creates hard or symbolic 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 command lists 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 |
--full-time | 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 command creates directories.
Synopsis
mkdir [<option>] directory ...Options
| Option | Description |
|---|---|
-m | Set permission mode (as in chmod). |
-p | No error if the directory already exists; create parent directories as needed. |
Examples
Create the directory /tmp/test/example, including any missing parent directories:
mkdir -p /tmp/test/examplemv
This command moves or renames 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 command prints the path of the current working 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
The readlink command is used to display the target of a symbolic link.
Synopsis
readlink FILEDescription
When given a symbolic link as an argument, readlink displays the path to which the symlink points. If the specified file is not a symbolic link, readlink produces no output.
Examples
Display the target of the symbolic link /usr/bin/report:
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 command removes 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 command removes 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 command filters and transforms 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 command deletes a file completely from non-volatile memory. It 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 the filesystems underlying the specified files. |
Examples
Flush all pending writes to disk:
syncSync only the data of a specific file:
sync -d /var/log/messagestail
This command outputs the last part of files.
Synopsis
tail [-n <number>] [-f] [file ...]Options
| Option | Description |
|---|---|
-n | Print the last N lines instead of the last 10 |
-f | Output appended 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 command creates, extracts, or lists files in a tar archive.
Synopsis:tar -[czxtvokO] [ -f tarfile ] [ -C dir ] [ file ] ...
Options:
| Option | Description |
|---|---|
c | Create an archive. |
x | Extract files from an archive. |
t | List the contents of an archive. |
-f FILE | Name of the archive file, or - for stdin. |
-C DIR | Change to directory DIR before performing the operation. |
-v | Verbosely list files processed |
-O | Extract to stdout |
-o | Do not restore user:group ownership. |
-k | Do not replace existing files. |
-z | (De)compress using gzip |
-a | (De)compress based on file extension. |
-h | Follow symlinks |
Examples:
Create a log.tar archive from the directory /var/log:
tar -cf log.tar /var/logExtract all files from the archive log.tar:
tar -xf log.tarCreate a compressed archive using gzip:
tar -czf log.tar.gz /var/logtouch
This command updates the timestamp of a file, or creates an empty file if it does not exist.
Synopsis:touch [-c] [-h] <file> [<file> ...]
Options:
| Option | Description |
|---|---|
-c | Do not create any files. |
-h | Do not follow symbolic links. |
Examples:
Create an empty file or update the timestamp of /tmp/test:
touch /tmp/testUpdate the timestamps of multiple files at once:
touch file1.txt file2.txt file3.txtvi
This command opens a text editor for creating or modifying files.
Synopsis:vi [-H] [<file> ...]
Options:
| Option | Description |
|---|---|
-H | List available features. |
Examples:
Open the file /etc/rc.local for editing:
vi /etc/rc.localwc
This command prints newline, word, and byte counts for each file, and a total line if more than one file is specified. With no file, or when the 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
xxd 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 displays the contents of gzip-compressed files without explicitly decompressing them first. It is equivalent to running gunzip -c.
Synopsis:zcat [file ...]
Description:zcat concatenates the uncompressed contents of compressed files to standard output. When no files are specified, or when the filename - is used, zcat reads from standard input. Since zcat is a symlink to gzip, additional gzip options may be passed.
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'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 backup data is written to standard output and can be redirected to a file using shell redirection, as shown in the examples below (the filename is not passed as a command argument). A previously saved configuration can be restored using the restore command, see Chapter restore for details.
The backup output is generated in a plain-text, key-value format that is suitable for storage, transfer, and later restoration. Sensitive data can optionally be filtered out or encrypted.
Synopsis:
backup [<options>] > <filename>Options:
| Option | Description |
|---|---|
-c | Back up the configuration excluding user account data (default if no option is specified). |
-u | Back up only user account data. |
-a | Back up the complete configuration, including user accounts, scripts, and Router Apps settings. |
-f | Filter sensitive information (passwords, keys, secrets, and passphrases 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 changes file and directory permissions (mode bits) in a Unix-like system. It allows you to control who can read, write, or execute a file or directory.
For a detailed explanation of permission modes and their numeric or symbolic notation, see chmod(1) — Linux manual page.
Synopsis:
chmod [-R] <mode> <filename>Options:
| Option | Description |
|---|---|
-R | Change permissions of files and directories recursively. |
Examples:
Make a script executable by its owner and readable by others:
chmod 755 /tmp/script.shAllow full access for the owner and read-only access for others:
chmod 744 /tmp/config.cfgChange permissions for all files in a directory recursively:
chmod -R 755 /opt/customchown
This command changes the user and/or group ownership of files and directories. It is commonly used by administrators to manage access rights and file control in Unix-like systems.
For detailed usage and syntax, see chown(1) — Linux manual page.
Synopsis:
chown [-R] <user>[:<group>] <filename>Options:
| Option | Description |
|---|---|
-R | Change ownership of files and directories recursively. |
Examples:
Change the owner of a file to user root:
chown root /tmp/config.cfgChange both owner and group of a directory recursively:
chown -R admin:admin /opt/customChange only the group of a file:
chown :network /tmp/log.txtchpasswd
This utility updates user passwords non-interactively, which is useful for bulk password updates or use 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 prints the connection log.
Synopsis:
clogExamples:
Display the connection log:
clogdate
This command displays the current date and time in the specified format, or sets 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 the time described by STRING, not the current time. |
-s | Set the 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:
dateSet the date and time to December 24, 2011 at 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 reports 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 the filesystem type. |
-t TYPE | Print only mounts of this type. |
Examples:
Display disk usage for all mounted filesystems:
dfDisplay disk usage including filesystem type:
df -Tdmesg
This command displays 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 the latest kernel log messages and clear the ring buffer:
dmesg -cDisplay kernel log messages with human-readable timestamps:
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 johnjohn:
When Type Source Valid
2024-07-25 12:31:22 RHOST 10.64.0.1 V
2024-08-22 11:30:30 RHOST 10.64.0.25 VView 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 updates 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 (restore configuration, complete firmware switch). |
-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 displays user and group information for the specified user, or for the current user if no user is specified.
Synopsis:
id [OPTIONS] [USER]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 report an error if no processes were found. |
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 prints kernel log messages.
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 |
|---|---|
-s | Log the message to standard error, as well as the system log. |
-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. |
Examples:
Send the message "System rebooted" to the syslogd daemon:
logger "System rebooted"Send 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 command sets up and controls loop devices.
Synopsis:
losetup [-rP] [-o OFS] {-f|LOOPDEV} FILE # associate loop devices
losetup -c LOOPDEV # reread file size
losetup -d LOOPDEV # disassociate
losetup -a # show status
losetup -f # show next free loop deviceOptions:
| Option | Description |
|---|---|
-o OFS | Start OFS bytes into FILE. |
-P | Scan for partitions. |
-r | Read-only. |
-f | Show/use next free loop device. |
Examples:
Show all active loop device associations:
losetup -aAssociate the next free loop device with an image file:
losetup -f /tmp/image.imgDetach the loop device /dev/loop0:
losetup -d /dev/loop0mount
This command mounts 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. |
For a detailed description of this command, refer to the Linux manual pages.
Examples:
Mount a USB flash drive to the directory /mnt:
mount -t vfat /dev/sda1 /mntConnect the contents of a USB flash drive formatted with the exFAT file system (e.g., in Microsoft Windows) to the directory /mnt:
mount -t exfat /dev/sda1 /mntMount a filesystem as read-only:
mount -r -t ext4 /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 command changes 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. |
Examples:
Find the PID of the sshd process:
pidof sshdFind a single PID of the dnsmasq process:
pidof -s dnsmasqps
This command displays information about currently running processes.
Synopsis:
ps [w] [l]Options:
| Option | Description |
|---|---|
w | Wide output. |
l | Long output. |
Examples:
Display currently running processes:
psDisplay processes with wide, long output:
ps w lrestore
This command restores a previously created router configuration from a backup file generated by the backup command, see Chapter backup. The backup file may be either plain text or encrypted.
During restoration, the configuration is validated, optionally decrypted, and then applied to the router.
Synopsis:
restore [-p <password>] <filename>Options:
| Option | Description |
|---|---|
-p <password> | Decrypt the backup file before restoration (required if the backup was created with backup -p). |
Notes
- The
<filename>must be provided as a normal command argument (unlikebackup, which uses output redirection). - If the backup is encrypted, the same password used during backup must be supplied with the
-poption. - When the configuration is changed, the system generates an internal configuration changed event.
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 prints emergency log messages.
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:
Follow the system log in real time:
slog -fDisplay the last 50 lines of the system log:
slog -n 50service
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, see Chapter doas.
sysctl
This command lists and modifies kernel parameters at runtime. The available parameters 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 the kernel.hostname parameter without printing the key name:
sysctl -n kernel.hostname
RouterSet the value of the kernel.domainname parameter:
sysctl -w kernel.domainname="example.com"
kernel.domainname = example.comtaskset
💡 This command is available only on the ICR-4xxx routers.
This command sets or retrieves the CPU affinity of a process — the set of CPU cores the process is allowed to run on. It can either launch a new program with the given affinity or change the affinity of an already running process. Pinning a demanding process to specific cores can help balance the system load.
Synopsis:
taskset [-ap] [HEXMASK | -c LIST] { PID | PROG ARGS }Options:
| Option | Description |
|---|---|
-p | Operate on an existing process specified by its PID instead of launching a new program. |
-a | Operate on all threads of the process. |
-c | Specify the affinity as a list of CPU cores (e.g., 0,2) instead of a hexadecimal mask. |
Examples:
Retrieve the CPU affinity of the process with PID 1234:
taskset -p 1234Restrict the process with PID 1234 to CPU cores 0 and 1:
taskset -cp 0,1 1234Launch a program restricted to the first CPU core (mask 0x1):
taskset 0x1 tcpdump -n -i eth0times
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 / memory / 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 shell built-in command sets or displays the default file permission creation mask. The umask determines which permissions are not set on newly created files and directories.
Synopsis:umask [OPTION]... [MODE]
Options:
| Option | Description |
|---|---|
-S | Display the current umask in symbolic format. |
-p | Display the output in a format reusable as input. |
Examples:
Display the current umask value:
umaskSet a new umask so that new files are accessible only by the owner:
umask 077Display the current umask in symbolic format:
umask -Sumount
This command unmounts 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:
Unmount the filesystem mounted at /mnt:
umount /mntUnmount a device by its device path:
umount /dev/sda1umupdate
This command installs, updates, or removes a Router App from the command line.
Synopsis:umupdate [-a <filename>] [-d <n>]
Options:
| Option | Description |
|---|---|
-a | Install or update a Router App. Specify the path to the installation file. |
-d | Remove an installed Router App with the specified name. The list of installed apps can be obtained with service module list. |
Examples:
Install a Python 3 Router App from an installation file:
umupdate -a /var/tmp/python3.v3.tgzRemove an installed Python 3 Router App:
~ # ls /opt
fota log_temp.csv python3 usrled_mgmt zabbix_agent
iperf3 pinger sleepmode webTerm
~ # umupdate -d python3Network 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:
View the ARP table without resolving IP addresses to domain names:
arp -nAdd a static ARP entry:
arp -s 192.168.1.100 00:11:22:33:44:55brctl
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 connects different Ethernet networks, making them appear as a single unified network to all connected devices.
Each connected network segment corresponds to a physical interface added to the bridge. These individual interfaces are bundled into one larger logical network, which corresponds to the bridge network interface itself.
Synopsis:
brctl [<command>]Commands:
| Command | Parameters | Description |
|---|---|---|
addbr | <bridge> | Creates a new bridge instance. |
delbr | <bridge> | Deletes an existing bridge. |
addif | <bridge> <device> | Adds a network interface (port) to a bridge. |
delif | <bridge> <device> | Removes a network interface from a bridge. |
setageing | <bridge> <time> | Sets the Ethernet address ageing time (in seconds). |
setbridgepri | <bridge> <priority> | Sets the bridge's priority for STP (Spanning Tree Protocol). |
setfd | <bridge> <time> | Sets the bridge's forward delay (in seconds). |
sethello | <bridge> <time> | Sets the time between hello packets for STP. |
setmaxage | <bridge> <time> | Sets the maximum message age for STP. |
setpathcost | <bridge> <port> <cost> | Sets the STP cost of a path via a specific port. |
setportprio | <bridge> <port> <priority> | Sets the STP priority for a specific port. |
show | — | Displays a list of all current bridge instances. |
showmacs | <bridge> | Displays a list of MAC addresses learned by the bridge. |
showstp | <bridge> | Displays the STP status for a bridge. |
stp | <bridge> {on | off} | Enables or disables the Spanning Tree Protocol on a bridge. |
Examples:
Create a bridge named br0 and add interfaces eth0 and eth1 to it:
brctl addbr br0
brctl addif br0 eth0
brctl addif br0 eth1Display the status of all configured bridges:
brctl showbridge
Tips
The bridge command is the modern, feature-rich utility for managing Ethernet bridges and their advanced features, such as VLAN filtering. It is part of the iproute2 suite and serves as the replacement for the legacy brctl command. For all new configurations, the use of ip and bridge is strongly recommended.
The bridge command allows for the configuration and inspection of bridge devices, ports, and VLAN settings. It works in conjunction with the ip command, which is used for creating the bridge device itself and for assigning interfaces to it.
Synopsis:
bridge [ OPTIONS ] OBJECT { COMMAND | help }Global Options:
| Option | Description |
|---|---|
-V, -Version | Displays the version of the bridge utility. |
-s, -stats | Displays more detailed statistics. |
-d, -details | Provides more detailed information in the output. |
-j, -json | Displays output in JSON format. |
-p, -pretty | Makes JSON output more human-readable. |
-o, -oneline | Formats output on a single line, which is useful for scripting. |
The bridge utility operates on several objects. The most common objects are link, mdb, and vlan.
Object: link
The link object is used to inspect and configure bridge ports.
| Command | Description |
|---|---|
show | Displays the status and configuration of all bridge ports. |
set dev <port> <args> | Sets various parameters for a specific port. Common arguments include: cost <value> (sets the STP path cost), priority <value> (sets the STP port priority), state <state> (sets the port state, e.g., forwarding), and vlan_filtering <0|1> (disables or enables VLAN filtering on the bridge device; must be set on the bridge interface, e.g., br0, not a port). |
Object: fdb
The fdb object manages the Forwarding Database, which contains the MAC address table for the bridge.
| Command | Description |
|---|---|
show [dev <bridge>] | Displays the FDB entries (MAC table) for a given bridge. |
add <MAC> dev <port> | Adds a permanent (static) MAC address entry to the FDB, associating it with a specific port. |
delete <MAC> dev <port> | Removes a MAC address entry from the FDB. |
append <MAC> dev <port> | Appends a static FDB entry that is externally learned. |
Object: vlan
The vlan object is used to configure VLAN filtering on bridge ports, which is a key feature not available in brctl. VLAN filtering must first be enabled on the bridge device itself using bridge link set dev <bridge> vlan_filtering 1.
| Command | Description |
|---|---|
show [dev <port>] | Displays the VLAN configuration for all ports or for a specific port. |
add vid <ID> dev <port> [pvid] [untagged] | Adds a VLAN to a port. vid <ID> is the VLAN ID to add; pvid marks this VLAN as the Port VLAN ID (native VLAN) so ingress untagged traffic is assigned to it; untagged sends egress traffic for this VLAN untagged. |
delete vid <ID> dev <port> | Removes a VLAN from a port. |
Examples:
Create a bridge, add ports, and bring it up. This uses the ip command, which is standard practice:
ip link add name br0 type bridge # Create a bridge device named br0
ip link set dev eth0 master br0 # Add eth0 to the bridge
ip link set dev eth1 master br0 # Add eth1 to the bridge
ip link set dev br0 up # Bring the bridge interface upEnable VLAN filtering on the bridge and configure VLANs on its ports:
bridge link set dev br0 vlan_filtering 1 # Enable VLAN awareness
bridge vlan add vid 100 dev eth1 # Allow tagged VLAN 100 on eth1
bridge vlan add vid 200 dev eth2 pvid untagged # Allow untagged VLAN 200 on eth2 (native VLAN)Display the VLAN configuration for the bridge:
bridge vlan 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 |
Expectation Options:
| Option | Description |
|---|---|
--tuple-src <ip> | Source address in expect tuple |
--tuple-dst <ip> | Destination address in expect tuple |
--mask-src <ip> | Source mask address |
--mask-dst <ip> | Destination mask address |
Conntrack and Expectation Options:
| Option | Description |
|---|---|
-s <ip> | Source address from original direction |
-d <ip> | Destination address from original direction |
-r <ip> | Source address from reply direction |
-q <ip> | Destination address from reply direction |
-p <proto> | Layer 4 Protocol, eg. 'tcp' |
-f <proto> | Layer 3 Protocol, eg. 'ipv6' |
-t <timeout> | Set timeout |
-u <status> | Set status, eg. ASSURED |
Examples:
Display the content of the conntrack table:
conntrack -LFlush (delete) all entries from the conntrack table:
conntrack -Fcurl
curl (Client URL) is a versatile tool for transferring data to or from a server. It supports HTTP, HTTPS, and FTP/FTPS. It is an alternative to wget, see Chapter wget.
Synopsis:
curl [options...] <url>Common Options:
| Option | Description |
|---|---|
-o <file> | Write the output to a specified file instead of stdout. |
-O | Write output to a local file named like the remote file we get. |
-I | Fetch the HTTP header only. Useful for checking if a link is alive or seeing server information. |
-L | If the server reports that the requested page has moved to a different location (3xx error), this option makes curl redo the request on the new location. |
-k | Allow insecure connections (ignore SSL certificate issues). Common on local networks with self-signed certificates. |
-u <user:pwd> | Specify the user name and password to use for server authentication. |
Curl is an extremely powerful tool with hundreds of options. For complete documentation, run curl --help or refer to the curl man page.
Examples:
Download a file, keeping the remote filename:
curl -O https://downloads.example.com/firmware.binCheck HTTP response headers without downloading the page:
curl -I https://www.google.comOutput:
HTTP/2 200 OK
Content-Type: text/html; charset=ISO-8859-1Call a web API with authentication (e.g., for Dynamic DNS update):
curl -u "admin:password123" "https://api.service.com/update?ip=1.2.3.4"dig
This command is a flexible tool for interrogating DNS name servers. It performs DNS lookups and displays the answers returned by the queried servers in a human-readable format. The output includes the question section, answer section, authority section, and additional section as appropriate.
The dig utility supports both IPv4 and IPv6 queries, various query types (A, AAAA, MX, NS, TXT, etc.), and advanced DNS features like DNSSEC validation, EDNS options, and encrypted transports (DoH/DoT).
For complete documentation of all options including extensive debug flags (+d-opt), query classes, and advanced features, see dig(1) — Arch Linux manual page.
Tips
The dig tool was added in firmware version 6.6.1.
Synopsis:
dig [@global-server] [domain] [q-type] [q-class] {q-opt}
{global-d-opt} host [@local-server] {local-d-opt}
[ host [@local-server] {local-d-opt} [...] ]Note: Global debug options (before hostname) affect all queries. Local debug options (after hostname) apply only to that specific lookup. Default query class is in and type is a.
Options:
| Option | Description |
|---|---|
-4 | Use IPv4 query transport only. |
-6 | Use IPv6 query transport only. |
-b address[#port] | Bind to source address/port. |
-c class | Specify query class (in,hs,ch,...). |
-f filename | Batch mode - read queries from filename. |
-h | Print help and exit. |
-k keyfile | Specify TSIG key file. |
-m | Enable memory usage debugging. |
-p port | Specify port number. |
-q name | Specify query name. |
-r | Do not read ~/.digrc. |
-t type | Specify query type (a,mx,ns,soa,...). |
-u | Display times in microseconds instead of milliseconds. |
-v | Print version and exit. |
-x dot-notation | Shortcut for reverse lookups (PTR queries). |
-y [hmac:]name:key | Specify named base64 TSIG key. |
Examples:
Basic domain lookup (A record):
dig example.comSpecify nameserver and query type:
dig @8.8.8.8 example.com MXIPv6-only AAAA query:
dig -6 example.com AAAAReverse DNS lookup using shortcut:
dig -x 93.184.216.34Custom port and query class:
dig -p 5353 chaos.example.com CH TXTDNSSEC validation with trace:
dig +trace +dnssec example.comMultiple queries with different options:
dig google.com +short ADNS over HTTPS:
dig +https example.comShow statistics and memory usage:
dig -m example.com +stats +multilinedhcrelay
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. |
Options available for both DHCPv4 and DHCPv6:
| Option | Description |
|---|---|
-c <hops> | Maximum hop count. When forwarding packets, dhcrelay discards packets which have reached a hop count of <hops>. Default is 10. Maximum is 255. |
-d | Force dhcrelay to run as a foreground process. |
-p <port> | Listen and transmit on port <port>. Default is port 67 for DHCPv4, or port 547 for DHCPv6. |
-q | Quiet mode. |
Options available in DHCPv6 mode only:
| Option | Description |
|---|---|
-I | Force use of the DHCPv6 Interface-ID option. This option is automatically sent when there are two or more downstream interfaces in use, to disambiguate between them. |
-l | Specifies the "lower" network interface for DHCPv6 relay mode: the interface on which queries will be received from clients or from other relay agents. |
-u | Specifies the "upper" network interface for DHCPv6 relay mode: the interface to which queries from clients and other relay agents should be forwarded. |
For help on the command line, type dhcrelay -h. For more information on this command, look up the man page on the Internet.
Warning
It is necessary to set at least two interfaces for sending/listening — see the example below.
Examples:
Relay DHCP requests from interfaces eth0 and eth1 to a DHCP server, the "upstream" server <server ip>. When a reply is received from upstream, it is multicast or unicast back downstream to the source of the original request:
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 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 Wake-on-LAN (WoL) Magic Packet to a network interface, which can wake up sleeping machines that support this feature. The target machine is identified by its MAC address.
Synopsis:
ether-wake [-b] [-i IFACE] [-p aa:bb:cc:dd[:ee:ff]] MACOptions:
| Option | Description |
|---|---|
MAC | The MAC address of the network card of the machine to be woken up. The address must be specified in the format 00:11:22:33:44:55. |
-b | Broadcasts the Magic Packet to all devices on the network segment. |
-i IFACE | Specifies the network interface through which the Magic Packet will be sent. If not specified, the default interface is eth0. |
-p PASSWORD | Appends a four or six-byte password to the Magic Packet for systems that require a SecureON password. The password should be specified in a MAC-like hex format, separated by colons. |
Examples:
Wake up a machine using the default eth0 interface:
ether-wake 00:11:22:33:44:55Wake up a machine, sending the packet through the eth1 interface:
ether-wake -i eth1 00:11:22:33:44:55Broadcast a Magic Packet to wake up a machine with a specific MAC address:
ether-wake -b 00:11:22:33:44:55Wake up a machine that requires a six-byte SecureON password:
ether-wake -p 11:22:33:44:55:66 00:11:22:33:44:55ethtool
This command displays or modifies Ethernet interface settings.
Synopsis:
ethtool [<option> ...] <devname> [<commands>]Options:
For a detailed description of this command, refer to the Linux manual pages.
Examples:
View the status of the interface eth0:
ethtool eth0Set interface eth0 to 10 Mbit/s half duplex:
ethtool -s eth0 speed 10 duplex half autoneg offEnable autonegotiation on interface eth0:
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
Go to Configuration → System → Identification in the router GUI if you want to change the hostname.
The hostname command is used to display the system's network name. In a network environment, this name helps to identify the router among other devices.
On this system, the hostname command is used solely for viewing the name. It finishes execution immediately and returns you to the shell prompt.
Synopsis:
hostname [-b]Options:
| Option | Description |
|---|---|
-b | Set hostname to localhost if it is otherwise unset/empty (boot default). |
Examples:
Display the current hostname:
hostnameOutput:
Routerifconfig
The ifconfig (interface configurator) utility is used to display or configure network interfaces. It allows you to assign IP addresses, enable or disable interfaces, and manage settings like MTU or promiscuous mode.
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.
Synopsis:
ifconfig [-a] <interface> [<option> ...]Options:
| Option | Description |
|---|---|
up | Activate the specified interface. |
down | Shut down the driver for the specified interface. |
netmask <addr> | Set the IP network mask for this interface. |
broadcast <addr> | Set the protocol broadcast address for this interface. |
mtu <NN> | Set the Maximum Transfer Unit (MTU) of an interface. |
promisc | Enable or disable (-promisc) promiscuous mode. If enabled, all packets on the network will be received by the interface. |
txqueuelen <NN> | Set the length of the transmit queue of the device. |
Examples:
View the status of all active interfaces:
ifconfigOutput:
eth0 Link encap:Ethernet HWaddr 00:11:22:33:44:55
inet addr:192.168.1.1 Bcast:192.168.1.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
...Set an IP address and bring up the interface:
ifconfig eth1 10.0.0.1 netmask 255.255.255.0 upCreate a virtual interface alias with a second IP address:
ifconfig eth0:0 192.168.2.1 netmask 255.255.255.0 upDisable the eth1 interface:
ifconfig eth1 downip
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.
For complete documentation of all sub-commands and advanced networking features (tunnels, xfrm, policy routing), see ip-address(8) — Arch Linux manual page.
Synopsis:
ip [options] <object> {command | help}Common Options:
| Option | Description |
|---|---|
-s | Statistics. Output more information (e.g., packet counts). Repeat for more detail. |
-o | Oneline. Output each record on a single line for easier parsing with grep or awk. |
-4 / -6 | Shortcut for IPv4 or IPv6 protocol family. |
Common Objects:
| Object | Description |
|---|---|
link | Network device (e.g., eth0, wlan0). Used to bring interfaces up or down. |
addr | IP addresses assigned to devices. |
route | Routing table entries. |
neigh | ARP or NDISC cache entries (neighbor management). |
Examples:
Display all interfaces and their IP addresses:
ip addr showDisplay the routing table:
ip route listAdd a static route via a gateway:
ip route add 192.168.3.0/24 via 192.168.1.2Bring the eth1 interface down:
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 the broadcast address, network address, and netmask for a /24 subnet:
ipcalc -bnm 192.168.1.100/24Output:
NETMASK=255.255.255.0
BROADCAST=192.168.1.255
NETWORK=192.168.1.0Example #2: Determine prefix length from a netmask. If you have a traditional netmask and need the CIDR prefix notation:
ipcalc -p 192.168.1.100 255.255.255.0Output:
PREFIX=24Example #3: Get only the netmask. Useful for scripts that need to extract a specific value:
ipcalc -m 192.168.1.100/26Output:
NETMASK=255.255.255.192iptables
The iptables utility is the administration tool for IPv4 packet filtering and NAT (Network Address Translation). It allows you to configure tables, chains, and rules that manage how the router handles incoming, outgoing, and forwarded traffic.
Iptables is a vast subject. For a detailed description of all commands, targets, and match extensions, refer to the official manual pages: iptables(8) — Linux manual page.
Synopsis:
iptables [-t table] [command] [chain] [match] [target]Key Features & Supported Modules:
- DSCP & QoS — Supports the
DSCPtarget anddscpmatch for Quality of Service (QoS) configurations based on packet marking. - CONNMARK — Allows marking entire connections rather than just individual packets. This is useful for complex routing and traffic shaping where only the first packet of a session needs to be inspected.
- String Match — Supports searching for specific text patterns within packets using the
stringextension. - U32 Match — An advanced module for matching arbitrary bytes at any offset within a packet.
- Statistic Module — Matches packets based on statistical conditions (e.g., matching every n-th packet or using a random probability).
To see which modules are currently available on your system, check the proc filesystem:
cat /proc/net/ip_tables_matchesExamples:
Port forwarding (DNAT) — redirect TCP port 8080 to an internal server. Redirect incoming TCP traffic from port 8080 to an internal server at 192.168.1.11 on port 80.
Add DNAT rule:
iptables -t nat -A pre_nat -p tcp --dport 8080 -j DNAT --to-destination 192.168.1.11:80Allow traffic in mangle table:
iptables -t mangle -A pre_nat -p tcp --dport 8080 -j ACCEPTExample #2: Quality of Service (DSCP marking). Mark outgoing traffic on port 81 with a specific DSCP value and then apply a firewall mark for routing.
Set DSCP value:
iptables -t mangle -I POSTROUTING -p tcp --dport 81 -j DSCP --set-dscp 0x0aMatch DSCP and set MARK:
iptables -t mangle -I POSTROUTING -m dscp --dscp 0x0a -j MARK --set-mark 81Example #3: Drop every second Ping (ICMP) packet. A demonstration of the statistic module using the nth mode:
iptables -I INPUT -p icmp -m statistic --mode nth --every 2 --packet 0 -j DROPiw
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:
Scan for available wireless networks on wlan0:
iw dev wlan0 scanDisplay the status of the current wireless link on wlan0:
iw dev wlan0 linkShow detailed information about all connected stations:
iw dev wlan0 station dumpShow capabilities of the physical device phy0:
iw phy phy0 infoAdd a virtual monitor interface:
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) |
Examples:
Open a TCP connection to port 42 of 192.168.3.1 using port 31337 as the source port with a 5-second timeout:
nc -p 31337 -w 5 192.168.3.1 42Listen on port 8080 and print received data:
nc -l -p 8080net-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 (for SNMP v1 and v2c). |
-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.2Sends an INFORM message to the SNMP manager specified by AGENT using SNMP version 2c and the community string "public".
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.3Sends an SNMPv3 INFORM message with authentication (SHA) and encryption (DES), using the specified usernames and passphrases.
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 6Uses SNMP version 1 to send an INFORM message with specified enterprise OID and trap parameters.
net-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 (for SNMP v1 and v2c). |
-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 ''Sends a test trap to the SNMP manager specified by AGENT using SNMP version 2c and the community string "public".
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.1Sends an SNMPv3 trap with authentication (SHA) and encryption (DES), using the specified usernames and passphrases.
net-snmptrap -v 2c -c public -C i AGENT '' 0 .1.3.6.1.4.1.8072.2.3.0.2 0 0 ''Uses the -C i option to send an INFORM message instead of a TRAP using SNMP version 2c.
netstat
The netstat (network statistics) command is a valuable troubleshooting tool used to display active network connections (sockets), routing tables, and network interface statistics.
Synopsis:
netstat [options]Options:
| Option | Description |
|---|---|
-l | Display only listening server sockets (wait for incoming connections). |
-a | Display all sockets (both listening and connected). |
-e | Display extended information. |
-n | Do not resolve names. Show IP addresses and port numbers numerically (this significantly speeds up the output). |
-r | Display the kernel routing table. |
-t | Filter for TCP sockets. |
-u | Filter for UDP sockets. |
-w | Filter for RAW sockets. |
-x | Filter for UNIX domain sockets. |
Examples
List all listening TCP and UDP ports numerically:
netstat -tulnCombining the -t, -u, -l, and -n flags is the most common way to see which services are currently waiting for connections on the router, without resolving DNS names:
netstat -tulnOutput:
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN
udp 0 0 0.0.0.0:53 0.0.0.0:*Example #2: Print the routing table. Use the -r flag to show the routing table. Adding -n prevents delays caused by DNS lookups on the gateway IP addresses:
netstat -rnOutput:
Destination Gateway Genmask Flags MSS Window irtt Iface
0.0.0.0 192.168.1.1 0.0.0.0 UG 0 0 0 eth0
192.168.1.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0nsupdate
The nsupdate command is a DNS update utility that allows dynamic updates to a zone using the DNS UPDATE protocol (RFC 2136). It reads commands from files or standard input to add, delete, or modify DNS resource records on a nameserver that supports dynamic updates.
Synopsis:
nsupdate [-CdDi] [-L level] [-l] [-g | -o | -y keyname:secret | -k keyfile] [-p port]
[-v] [-V] [-P] [-T] [-4 | -6] [filename]Options:
| Option | Description |
|---|---|
-C | Check names processing. |
-d | Debug mode. |
-D | Debug level. |
-i | Interactive mode. |
-L level | Set logging level. |
-l | Localhost mode (default server/zone). |
-g | GSS-TSIG authentication. |
-o | GSS-TSIG ownername mode. |
-y keyname:secret | Direct TSIG key specification. |
-k keyfile | Specify TSIG key file for authentication. |
-p port | Specify destination port. |
-v | Verbose output. |
-V | Print version. |
-P | Primary server only. |
-T | Use TCP transport. |
-4 | Use IPv4 transport only. |
-6 | Use IPv6 transport only. |
[filename] | Read update commands from specified file (or stdin). |
Examples:
Update a DNS A record using a TSIG key (the send command is required):
nsupdate -k ddns-key.txt <<EOF
update delete routerX.example.com A
update add routerX.example.com 200 A 1.2.3.4
send
EOFExample #2: Interactive mode with verbose output. Start an interactive session to type commands manually:
nsupdate -vExample #3: Update from a command file. Read a list of update commands from a text file. Ensure the file contains the send command at the very end:
nsupdate -4 updates.txtExample #4: Localhost zone updates. Update the zone on the local server without specifying credentials:
nsupdate -lntpdate
This command synchronizes 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 command sends ICMP echo requests to a network host to test connectivity.
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:
Send a single ICMP echo request with a 500-byte payload to 10.0.0.1:
ping -c 1 -s 500 10.0.0.1Continuously ping a host to check connectivity:
ping 192.168.1.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 command displays and manipulates 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:
Display the routing table without resolving IP addresses:
route -nAdd a route for the network 192.168.3.0/24 through eth0:
route add -net 192.168.3.0/24 dev eth0Add a route for a specific host via a gateway:
route add -host 192.168.3.1 gw 192.168.1.2Set the default gateway:
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. |
Tips
The scp utility exits 0 on success, and >0 if an error occurs.
Examples:
Copy a file from a remote host to the local machine:
scp root@remotehost.edu:/etc/version ~/myFolderCopy a file from the local machine to a remote host:
scp /etc/version root@remotehost.edu:~/Copy a directory recursively to a remote host:
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:
Calculate and display all information for an IPv4 address:
sipcalc -a 192.168.1.1/24Split an IPv6 network into smaller subnets:
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 i 2snmptrap
Tips
See similar programs snmpinform and snmptrap.
This command sends an SNMP trap.
Synopsis
snmptrap [-c <community>] [-g <generic>] [-s <specific>] [-R] <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.
tcpdump
This command captures and displays network traffic.
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 command establishes an interactive session with a remote host using the Telnet protocol.
Synopsis
telnet <host> [<port>]Examples
Connect to 192.168.1.2 by protocol Telnet.
telnet 192.168.1.2traceroute
This command traces the network route to a remote host.
Synopsis
traceroute [-Flnrv] [-f <1st_ttl>] [-m <max_ttl>] [-p <port#>] [-q <nqueries>]
[-s <src_addr>] [-t <tos>] [-w <wait>] [-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 |
-v | Verbose output |
Examples
Trace the route to a remote host:
traceroute 8.8.8.8traceroute to 8.8.8.8 (8.8.8.8), 30 hops max, 46 byte packets
1 192.168.1.1 (192.168.1.1) 1.014 ms 0.921 ms 0.878 ms
2 10.0.0.1 (10.0.0.1) 8.342 ms 8.251 ms 8.198 ms
3 * * *
4 72.14.194.34 (72.14.194.34) 19.443 ms 19.381 ms 19.302 ms
5 8.8.8.8 (8.8.8.8) 19.451 ms 19.367 ms 19.289 msTrace the route without resolving hostnames (faster output):
traceroute -n 8.8.8.8Trace the route using ICMP instead of UDP (useful when UDP is filtered):
traceroute -I 8.8.8.8Limit the trace to a maximum of 15 hops:
traceroute -m 15 192.168.100.1Specify a source interface and send only 1 probe per hop:
traceroute -i eth0 -q 1 10.0.0.1traceroute6
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 command creates and removes 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 the eth0 interface:
vconfig add eth0 1Remove a VLAN interface:
vconfig rem 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 if the URL exists (do not download the file). The exit status ($?) is 0 if the file exists. |
-c | Continue retrieving a partially downloaded file (resume an aborted transfer). |
-q | Quiet mode. Turn off all output, including error messages. |
-P DIR | Save the downloaded file to the specified directory <DIR> instead of the current working directory. |
-S | Print the HTTP or FTP server response headers. |
-T SEC | Set the network read timeout to <SEC> seconds. |
-O FILE | Save the downloaded document as <FILE>. Use - to write to standard output (stdout). |
-o FILE | Log all messages and output to <FILE> instead of the terminal. |
-U STR | Identify as <STR> in the User-Agent HTTP header. |
-Y on/off | Explicitly turn the use of a proxy server 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 on a server without downloading it:
wget --spider http://10.0.0.1/my.cfgOutput:
0Scripting/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> ...]Note: Program can be inline or from file (-f). Multiple -f options allowed.
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 }'Output:
192.168.1.1break
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 strings to standard output. It supports basic escape sequence interpretation and newline control.
Synopsis:
echo [-n] [-e] [-E] [<string> ...]Note: Multiple strings are concatenated with spaces. Backslash escapes are processed only with -e.
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 ...]Note: All arguments are concatenated (separated by spaces) into a single string, then parsed and executed as shell commands.
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]Note: Without arguments, exec reopens stdin/stdout/stderr from the shell's current redirections.
Options:
| Option | Description |
|---|---|
command [arguments] | Replace shell with specified command (no return). |
(no arguments) | Reopen stdin/stdout/stderr using current redirections. |
-a name | Set argv[0] of executed program to name. |
-l | Place a dash at start of argv[0] (login shell). |
Examples:
Replace the shell with the vi editor:
exec vi /etc/settings.pppReplace the shell with a new shell instance:
exec /bin/shRedirect all output of the script to a log file:
exec > /tmp/script.log 2>&1
echo "This goes to the log"Exec with a custom argv[0]:
exec -a mysh /bin/shexit
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).
Options:
| Option | Description |
|---|---|
[n] | Exit status code (0-255, default: last command status). |
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.
Options:
| Option | Description |
|---|---|
NAME[=VALUE] | Set and/or export environment variable(s). |
(no arguments) | List all currently exported variables. |
-p | List in portable format (export NAME=VALUE). |
-n | Remove NAME from exported list. |
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.
Note: Accepts only numeric input. Outputs result to stdout.
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.
Note: Variables in expressions do not need a $ prefix. Expressions must be quoted to prevent shell expansion.
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] ...]Note: Can only be used inside functions. Variables remain local to function scope.
Options:
| Option | Description |
|---|---|
name[=value] | Declare local variable with optional initial value. |
- | Restore local variables from stack (advanced usage). |
Examples:
Local variable in function:
myfunc() { local temp=10; echo $temp; }; myfuncOutput: 10
Local variable in function:
f() { local x=5 y=10; echo $((x+y)); }
fOutput: 15
Prevent global namespace pollution:
foo() { local counter=1; counter=$((counter+1)); echo $counter; }
fooOutput: 2
nohup
nohup is short for "No Hang-up". This command runs a program immune to hangups, with output redirected to nohup.out by default. The program continues running even after the user logs out.
Synopsis:
nohup <program> [<arguments>]Note: Output is redirected to nohup.out unless redirected elsewhere. Exit status is returned when the program completes.
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 (C printf syntax). It provides precise control over output formatting including numbers, strings, and escape sequences.
Synopsis:
printf FORMAT [ARGUMENT...]Note: FORMAT string uses C-style conversion specifiers. Unlike echo, no automatic newline is added.
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 reads one line from standard input (stdin) and assigns values to shell variables. 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"Raw mode (preserve backslashes):
read -r lineInput: path\to\config.ini
echo "$line"Output: path\to\config.ini
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 used 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]Options:
| Option | Description |
|---|---|
n | Exit status (0-255, default 0) |
Examples:
Return success from function:
check_file() { [ -f /etc/passwd ] && return 0; }
check_file && echo "OK"Output: OK
Return success status:
divide() { [ $2 -eq 0 ] && return 1; return 0; }Output: (nothing)
Return error status:
divide 10 0 && echo "OK" || echo "Error: $?"Output: Error: 1
Return error/success message:
divide 10 1 && echo "OK" || echo "Error: $?"Output: OK
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:
Multi-script coordination:
Script 1: shlock /tmp/config.txt; sleep 10; echo "Done"
Script 2: shlock /tmp/config.txt (waits 10s until Script 1 finishes)
Lock released automatically when script process terminates.
set
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:
Set positional parameters:
set -- file1 file2 file3
echo $1 $2 $3Output: file1 file2 file3
Enable exit-on-error in a script:
set -e; false; echo "This won't print"(script exits immediately, echo is not printed)
Enable command tracing:
set -x
ls /tmpOutput:
+ ls /tmp(shows each command as executed)
Disable tracing:
set +xOutput: + set +x
shift
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; echo $1 $2 $3; shift 2; echo $1 $2 $3Output:
a b c
c d eCheck the number of remaining arguments. The $# variable holds the count of current positional parameters. Continuing from the previous example (where 3 arguments remained):
echo "Arguments remaining: $#"Output: Arguments remaining: 3
sleep
The sleep command pauses the execution of a script or process for a specified amount of time. The time must be specified as an integer number of seconds.
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]or
. <filename> [arguments]Note: The . (dot) command is a synonym for source in POSIX shells.
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:
-f FILE: Returns true if the file exists and is a regular file.-d FILE: Returns true if the file exists and is a directory.-e FILE: Returns true if the file exists (regardless of type).-z STRING: Returns true if the length of the string is zero.-n STRING: Returns true if the length of the string is non-zero.s1 = s2: Returns true if the strings are equal.s1 != s2: Returns true if the strings are not equal.n1 -eq n2: Returns true if integers are equal.n1 -ne n2: Returns true if integers are not equal.n1 -gt n2: Returns true if n1 is greater than n2.n1 -ge n2: Returns true if n1 is greater than or equal to n2.n1 -lt n2: Returns true if n1 is less than n2.n1 -le n2: Returns true if n1 is less than or equal to n2.! <expr>: Returns true if the expression is false (negation).
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.
To list currently defined traps:
trapCommon Signals:
SIGINT (2): Interrupt signal (typically sent by pressingCtrl+C).SIGTERM (15): Termination signal. Requests the program to end gracefully.SIGHUP (1): 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:
Ensure cleanup on exit. This script creates a temporary file and ensures it is deleted even if the user presses Ctrl+C. Note that we trap EXIT, SIGINT, and SIGTERM to ensure the cleanup runs in all cases:
#!/bin/sh
TEMP_FILE="/tmp/data.tmp"
# Define cleanup function
cleanup() {
echo "Cleaning up temporary files..."
rm -f "$TEMP_FILE"
exit
}
# Register the trap for EXIT and signals
trap cleanup EXIT SIGINT SIGTERM
touch "$TEMP_FILE"
echo "Working... (Press Ctrl+C to test cleanup)"
sleep 10Ignore a signal. To ignore a signal (e.g., to prevent a script from stopping if the terminal closes), use an empty string as the action:
trap '' SIGHUPReset signal to default. To revert the signal handling back to the system default, use a hyphen (-):
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.
By default, unset tries to unset a variable. If you want to explicitly unset a function, use the -f option.
Synopsis:
unset [-v] [-f] <name>Examples:
Delete a variable. Define a variable, display it, then remove it:
CITY="Prague"
echo "City is: $CITY"Output: City is: Prague
unset CITY
echo "City is: $CITY"Output: City is:
Delete a function. Define a function and then remove it using the -f flag:
hello() {
echo "Hello World"
}
helloOutput: Hello World
unset -f hello
helloOutput: -sh: hello: not found
wait
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
The watch command is used to run a specified program periodically, showing its output in real-time. This is useful for monitoring status changes, such as network connections, process lists, or file sizes, without manually re-running the command.
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:
Monitor active network connections. Every 5 seconds, display the current listening ports and active connections using netstat. Run watch with 5-second interval (exit the command by pressing Ctrl+C):
watch -n 5 netstat -tuplnOutput (Header included):
Every 5.0s: netstat -tupln 2026-02-12 12:45:01
(netstat output follows...)Monitor system memory without header. Use the -t option to display only the raw output of the free command, updated every 2 seconds. Run watch without header (exit the command by pressing Ctrl+C):
watch -t freeOutput:
total used free shared buff/cache available
Mem: 1008460 149408 802824 372 56228 845280
Swap:xargs
The xargs command reads items from standard input (delimited by blanks or newlines) and executes a specified command using those items as arguments. It is commonly used in pipelines to process lists of files generated by commands like find or ls.
Synopsis:xargs [<commands>] [<options>] [<args> ...]
Options:
| Option | Description |
|---|---|
-o | Reopen stdin as /dev/tty. This is necessary if you want to run interactive applications (like a text editor) via xargs. |
-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:
Limit arguments per command. Use the -n option to process items in groups. In this example, we echo two numbers at a time:
printf "1 2 3 4 5 6" | xargs -n 2 echo "Pair:"Output:
Pair: 1 2
Pair: 3 4
Pair: 5 6Delete files found by find. Find files named core in /tmp and delete them. The -r option ensures rm is not run if no files are found. Note: This method may fail if filenames contain spaces or newlines.
find /tmp -name core -type f -print | xargs -r rm -f