Skip to content

Instantly share code, notes, and snippets.

@MahdiBM
Last active April 21, 2022 17:08
Show Gist options
  • Save MahdiBM/0608eecda6a97e00b15ff63c89bf499a to your computer and use it in GitHub Desktop.
Save MahdiBM/0608eecda6a97e00b15ff63c89bf499a to your computer and use it in GitHub Desktop.
Drop Caches Shell (Ubuntu 20.04)
#!/usr/bin/env swift
import Foundation
// Drops caches if (freeRam / totalRam) < 0.2
print("Program started")
let pipe = Pipe()
let free = Process()
free.executableURL = URL(fileURLWithPath: "/usr/bin/env")
free.arguments = ["free"]
free.standardOutput = pipe
do {
try free.run()
free.waitUntilExit()
print("Got `free` info")
let data = pipe.fileHandleForReading.readDataToEndOfFile()
if let output = String(data: data, encoding: String.Encoding.utf8) {
print("`free` said:", output, separator: "\n")
let comps = output
.replacingOccurrences(of: "\n", with: " ")
.components(separatedBy: " ")
.filter({ !$0.isEmpty })
if let totalRam = Double(comps[7]), let freeRam = Double(comps[9]) {
let ratio = freeRam / totalRam
if ratio < 0.2 {
print("Will try to drop caches; Total: \(totalRam), Free: \(freeRam), Ratio: \(ratio)")
let pipe = Pipe()
let dropCaches = Process()
dropCaches.executableURL = URL(fileURLWithPath: "/usr/bin/env")
dropCaches.arguments = ["bash", "-c", String(format: "%@", ("echo 1 | sudo tee /proc/sys/vm/drop_caches" as! CVarArg))]
dropCaches.standardOutput = pipe
do {
try dropCaches.run()
dropCaches.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
if let dropOutput = String(data: data, encoding: String.Encoding.utf8) {
if dropOutput.replacingOccurrences(of: " ", with: "")
.replacingOccurrences(of: "\n", with: "") == "1" {
print("Dropping process was successful")
} else {
print("Cannot confirm that the dropping process was successful;"
+ " process output: \(dropOutput.debugDescription)")
}
} else {
print("Caches drop process output was not a valid UTF8 String;"
+ " Cannot confirm that the dropping process was successful")
}
} catch {
print("Could not drop caches with the following error: \(error)")
}
} else {
print("Ram looking good; Total: \(totalRam), Free: \(freeRam), Ratio: \(ratio)")
}
} else {
print("Could not parse the output: \(output.debugDescription)")
}
} else {
print("`free` command answer is not a valid UTF String")
}
} catch {
print("`free` command failed with following error: \(error)")
}
print("Program ended")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment