fork download
  1. # Sanitize string for shell commands - http://stackoverflow.com/q/33905127/5290909
  2.  
  3. String.class_eval do
  4. def sanitizeshell()
  5. # Escape every character except letters and shell special chars
  6. self.gsub!(/[^\s"-*,-<>-~\u00FF]/, '\\\\\0')
  7. end
  8. def escapenonascii()
  9. # Escape every character outside the ASCII range
  10. self.gsub!(/[[:^ascii:]]/, '\\\\\0')
  11. end
  12. end
  13.  
  14.  
  15.  
  16. # Test it
  17. str = "(dir *.txt & dir *Sè\u00E1ñ*.rb) | sort /R >Filé.txt 2>&1"
  18. puts 'String:'
  19. puts str
  20.  
  21. puts "\nSanitized:"
  22. puts str.sanitizeshell
Success #stdin #stdout 0.05s 9696KB
stdin
Standard input is empty
stdout
String:
(dir *.txt & dir *Sèáñ*.rb) | sort /R >Filé.txt 2>&1

Sanitized:
(dir *.txt & dir *S\è\á\ñ*.rb) | sort /R >Fil\é.txt 2>&1