Manual:Scripting Tips and Tricks

From MikroTik Wiki
Revision as of 09:19, 24 August 2018 by Marisb (talk | contribs) (Created page with "{{Versions| any}} __TOC__ ===How to define empty array=== ===Get values for properties if 'get' command is not available=== For example, how do you get usable output fo...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
Version.png

Applies to RouterOS: any

How to define empty array

Get values for properties if 'get' command is not available

For example, how do you get usable output for scripting from <cmd>/interface wireless info hw-info</cmd> command? Use as-value:

[admin@1p_DUT_wAP ac] /interface wireless info> :put [hw-info wlan1 as-value ]
ranges=2312-2732/5/b;g;gn20;gn40;2484-2484/5/b;g;gn20;gn40;rx-chains=0;1;tx-chains=0;1

Output is 1D array so you can easily get interested property value

[admin@1p_DUT_wAP ac] /interface wireless info> :put ([hw-info wlan1 as-value ]->"tx-chains")      
0;1


Always check what value and type command returns

Lets say we want to get gateway of specific route using "as-value", if we execute following command it will return nothing

[admin@rack1_b36_CCR1009] /ip address> :put ([/ip route print as-value where gateway="ether1"]->"gateway") 


Command assumes that output will be 1D array from which we could extract element "gateway".

At first lets check if print is actually find anything:

[admin@rack1_b36_CCR1009] /ip address> :put ([/ip route print as-value where gateway="ether1"])  
.id=*400ae12f;distance=255;dst-address=111.111.111.1/32;gateway=ether1;pref-src=111.111.111.1

So obviously there is something wrong with variable itself or variable type returned. Lets check it more closely:

[admin@rack1_b36_CCR1009] /ip address> :global aa ([/ip route print as-value where gateway="ether1"
])       
[admin@rack1_b36_CCR1009] /ip address> :environment print 
aa={{.id=*400ae12f; distance=255; dst-address=111.111.111.1/32; gateway={"ether1"}; pref-src=111.11
1.111.1}}

Now it is clear that returned value is 2D array with one element. So the right sequence to extract gateway will be:

  • get 2d array
  • get first element
  • get "gateway" from picked element
[admin@rack1_b36_CCR1009] /ip address> :put ([:pick [/ip route print as-value where gateway="ether1"] 0]->"gateway")  
ether1

Be careful when adding array to string

If you want to print an array or add an array to existing string, be very careful as it may lead to unexpected results. For example:


[ Top | Back to Content ]