shellQuote function
Quote a string for safe shell usage.
Uses single quotes by default. If the string contains single quotes,
uses the $'...' ANSI-C quoting form. If the string is a simple
alphanumeric/dash/underscore string, returns it unquoted.
Implementation
String shellQuote(String input) {
if (input.isEmpty) return "''";
// Check if quoting is needed at all.
if (RegExp(r'^[a-zA-Z0-9._/=:@%^,+-]+$').hasMatch(input)) {
return input;
}
// If no single quotes, wrap in single quotes.
if (!input.contains("'")) {
return "'$input'";
}
// Use $'...' form for strings with single quotes.
final escaped = input
.replaceAll('\\', '\\\\')
.replaceAll("'", "\\'")
.replaceAll('\n', '\\n')
.replaceAll('\t', '\\t')
.replaceAll('\r', '\\r')
.replaceAll('\x07', '\\a')
.replaceAll('\b', '\\b')
.replaceAll('\x1B', '\\e');
return "\$'$escaped'";
}