My good friend Greg was asking about how to store data to files onboard a MikroTik device so I thought I’d elaborate here with some information and examples.
Before we get started, some things to note:
- While you can fetch and read the contents of any file, you are limited to working with 4096 character files as this is a limitation on the amount of information that can be contained in a string variable in RouterOS at this time.
- When creating new files in RouterOS via terminal the extension .txt will be appended to anything that doesn’t already have .txt at the end.
- You can work with newlines \n\r as delimeters (which is super helpful when downloading something list of IP addresses from somewhere)
The basic commands for working with a file, using variables in place of static content or file names:
1. To create a new file
/file print file=$filename
2. To read an existing file
:set $filedata [/file get $filename contents]
3. To write to an existing file
/file set $filename contents=$newdata
4. To append to an existing file
/file set $filename contents=([get $filename contents] . $newdata)
2 thoughts on “The basics of reading and writing files in RouterOS”
Your “The basics of reading and writing files in RouterOS” assumes knowledge of the Mikrotik scripting language (which is crappy). Minor improvements would make it much better. For example “To read an existing file” also needs: ” ; :put $filedata” to actually work. PLEASE, do not follow in Mikrotik’s steps.
No problem, that’s why I do a MUM presentation designed to teach and get people interested in the basics of MikroTik scripting – you can watch it here: https://www.youtube.com/watch?v=F-q4F3WhBjA