MikroTik Scripting Cheat Sheet: MikroTikScripting.
com
Hello World Loops Key Topic: Code Comments Functions
# file: hello.rsc # "for" loop # single line comment (ends at end-of-line) # define a function
# Hello World Script :for LoopCount from=1 to=10 do={ :global TimeNowFunc do={
:local Message "Hello World!"; :put "Current loop count = $LoopCount"; # comments cannot span multiple lines :return [/system clock get time];
:put $Message; :delay 1; # therefore multiple comments are required for }
} # a comment block
> /import hello.rsc # print current time
Hello World :put "hello"; # inline comments are useful too :local CurrentTime [$TimeNowFunc];
# "foreach" loop :put ("The time now is: $CurrentTime");
:local MyFruit {"apples"; "plums"; "pears"};
Local Variables # function to calc time
# print out each fruit Strings :global TimeInXMins do={
:foreach Fruit in=$MyFruit do={ :local TimeInterval [:totime "00:$1:00"];
# Create local variable with :put "I like $Fruit as a snack"; :local TimeNow [/system clock get time];
# assigned value } # Concatenation
:local BookTitle "Jaws"; :local Food "Chips"; return ($TimeNow + $TimeInterval);
:local Meal ("Fish and " . $Food); }
# Print variable value # "while" loop :put $Meal;
:put $BookTitle; :local TimeNow [/system clock get time]; :local Interval 10;
:local EndTime ($TimeNow + 00:00:10); # Substitution :put ("The time in $Interval mins is " .
# update variable value :local NiceFood "Pizza"; [$TimeInXMins $Interval]);
:set BookTitle "War and Peace"; :put "Starting 10 sec delay timer…"; :put "I love $NiceFood";
# Clear value :while ([/system clock get time] < $EndTime) do={ Operators
:set BookTitle; :delay 1; # find & extract subs-string
} :local InterfaceName "ether1-WAN"; # command operator []
# Note: local vars only exist for :local DashLoc [:find $InterfaceName "-"]; :local Ver [/system resource get version];
# lifetime of a script. :put "Timer expired!"; :put [:pick $InterfaceName 0 $DashLoc];
# substitution $
# "do-while" loop :put "99 + 100 is $(99+100)";
Global Variables :local Temperature 15; :put "the time is $[/system clock get time]";
:do { Arrays
:put "The temperature is: $Temperature "; # grouping operator ()
# Create global variable with } while= ( $Temperature < 12); :put ((10 + 3) * 10);
# assigned value # simple list
:global NumPages 278; # Note: loop executed once even though initial :local Fruit { "apple"; "orange"; "pear" }; # regex ~
# condition is false :put [/interface find where name ~ "^eth"];
# Print variable value # key/pair array
:put $NumPages; :local Interface { name="ether"; speed="1gbps" }; # Addition (std math)
# update variable value
If Statements :put (99 + 1);
# concatenate arrays
:set NumPages ($NumPages + 2); :local Array1 { 10; 20; 30; }; # Addition (IP math)
# "if" statement :local Array2 { 40; 50; 60 }; :put ("300th host: " . (192.168.0.0 + 300));
# Clear value :local TimeNow [/system clock get time]; :local BigArray ( $Array1, $Array2 );
:set NumPages; # Division (always integer result)
# additional greeting if before noon # access array elements (0 = first element) :put (5 / 2);
# Note: global vars exist until :if ($TimeNow < 12:00:00) do={ :local FirstFruit ($Fruit->0);
# cleared and can be shared :put "Good morning."; :local InterfaceName ($Interface->"name"); # In (host add in IP network)
# between scripts } :put (10.6.0.1 in 10.0.0.0/12);
# empty array
# print out current global vars :put "Have a good day!"; :local EmptyArray [:toarray ""]; # Bitwise and (&)
/environment print :put ("Network is : " . 192.168.7.55 & \
255.255.254.0);
# "if-else" statement
Key Topic: Variable Names
:local TimeNow [/system clock get time]; Key Topic: Variable Scopes
:if ($TimeNow < 12:00:00) do={ The MikroTik Scripting
# suggested convention: :put "Good morning."; Global Scope: exists between start and end of book is available on
} else={ every script (can be only one global scope per
Amazon.
:local DayOfWeek "Saturday"; :put "Good afternoon/evening." script).
:local MULTIPLIER 10; # constant }
Local Scope: unique local scope exists between
:local PingFunc; # function Find out more at:
:put "Have a good day!"; each pair of curly braces. Multiple local scopes
may exist, with child/parent relationships formed MikroTikScripting.com
by embedded local scopes.
V1.02 (Latest version? Check at https://MikroTikScripting.com/cheatsheet)
Global Commands Data Types Logical Operators
:beep <freq> <length> A sequence (list) of values, e.g. { "apple"; ! not
array
"orange"; 5 }
:delay <time> &&, and and
bool A true or false value (Boolean)
:do { <commands> } on-error={ <commands> } ||, or or
A unique hexadecimal value assigned to
:do { <commands> } while=( <conditions> ) id each config item. Also called an internal in in
ID. e.g. *100
:environment print
ip An IPv4 address. e.g. 192.168.1.1 Concatenation Operators
:error <output>
An IPv6 address. e.g. "." Joins two strings
ip6
FE80::260:3EFF:FE21:D370
:execute <expr> [file=<name>] Joins two arrays or adds an element to an
","
ip6-prefix An IPv6 prefix e.g. 2001:DB8:0:1::/64 array
:execute script=<name>
:find <str> <sub-str> <start>
ip-prefix An IP prefix, e.g. 192.168.2.0/24 Miscellaneous Operators
Returned by some commands to indicate
:for <var> from=<int> to=<int> step=<int> nil Returns output of single command, for
an empty result [] use in expressions or cmd substitution
do={ <commands> }
If a variable has no value, then it returns
:foreach <var> in=<array> do={ <commands> } nothing Returns output of a grouped operation,
a "nothing" value () for use in expressions or cmd substitution
:global <var> [<value>] num A 64bit signed integer, e.g. 100, -5, 3000
Returns the value of a variable or
$ expression. Used in substitution
:if (<condition>) do={<commands>} A sequence of alphanumeric characters.
str
e.g. "ether1-WAN1"
A matching operator that uses POSIX
:if (<condition>) do={<commands>} ~ extended regular expression matching
else={<commands>} time A time value. e.g. 18:48:00 ( 6:48PM)
:len <expression>
-> Retrieves an array element
Arithmetic Operators
:local <var> [<value>] Regex Metacharacters
+ Addition
:log <topic> <message> . Match single character
- Subtraction
:parse <expression> [] Match chars in braces
* Multiplication
:pick <str> <start>[<end>] [^] Match chars NOT in braces
/ Division
:pick <array> <start>[<end>]
% Modulo (division remainder) | Add OR logic to pattern
:return <value>
- Negation ^ Match beginning of string
:resolve <arg>
Note: results are always an integer $ Match end of string
:retry command=<expr> delay=[num] \
max=[num] on-error=<expr> Comparison Operators + Match one or more instances of char
:rndnum from=[num] to=[num] < Less than * Match zero or more instances of char
:rndstr from=[str] to=[num] > Greater than * Match zero or one instances of char
:set <var> [<value>] = Equal to
Escape Sequences
:terminal <operation> <= Less than or equal to
\" Literal quote character
:time <expression> >= Greater than or equal to
\\ Literal backslash
:timestamp != Not equal to
\n Newline
:toarray <var> Note: result is always boolean (true / false)
\r Carriage return
:tobool <var>
Bitwise Operators
\t Horizontal tab
:toid <var>
~ Invert all bits
\$ Literal $ (prevents var substitution)
:toip <var>
| Perform binary OR on all bits
\? Literal ? (prevents help system trigger)
:toip6 <var>
^ Perform binary XOR on all bits
\_ Insert space character
:tonum <var>
& Perform binary AND on all bits
\a BEL (0x07) character
:tostr <var>
<< Left shift binary specified num bits
\b Backspace (0x07) character
:totime <var>
>> Right shift binary specified num bits
\f Form feed (0xFF) character
:typeof <var>
\v Vertical tab
:while ( <condition> ) do={ <commands> }
\xx Character with ascii hex value xx