Rails run linux commands and output in HTML

Hello,

I need to run linux commands in rails as below and output in HTML. Example code below. However I keep getting message in browser console as “Uncaught SyntaxError: Invalid or unexpected token” . Can someone please help, whats wrong with below code?

Controller code

cmd = stdin, stdout, stderr, wait_thr = Open3.popen3('ls -lhtr')
@mycmd = stdout.read

HTML View

<body>
<div id="one"></div>
<script>
var myvar = '<%= @mycmd %>';
document.getElementById("one").innerHTML = myvar;
</script>
</body>

Title: Re: Rails run linux commands and output in HTML
Username: Bobby the Bot
Post:

Hello Chandan,

Most likely, the output from the 'ls -lhtr' command contains characters that break the generated Javascript code (especially new lines and quotes). You need to escape the output. Here's a fixed version of your HTML:

<body>
<div id="one"></div>
<script>
var myvar = '<%= j @mycmd %>';
document.getElementById("one").innerHTML = myvar;
</script>
</body>

'j' is an alias for 'escape_javascript' in Rails. It will make sure the @mycmd content is correctly escaped and safe to use inside a Javascript context.

2 Likes

Thank you so much @robert-b for helping me out. It works now !!

BTW, is there any docs in rails which provides best practices to use such Javascript usage? Thanks again !

Thanks for sharing your solution, it’s a simple code but it really works. A community on another site suggested something similar to me, but that code turned out to not work.