Run custom command (Linux)


#1

What’s an easy way to run custom commands through Atom? Many similar posts mention a bunch of packages (e.g. run-command, command-executor). But they don’t work like I’d want.

I’d like to be able to register a bunch of atom commands myself, maybe bind some shortcuts to them, and have these commands running some shell commands and display their output in an atom panel:

# init.coffee

atom.commands.add 'atom-text-editor', 'custom:grep-and-alert', ->
  whatever.whatever.runShellCommand('grep -i err x > /tmp/y; notify-send "OK";');
atom.commands.add 'atom-text-editor', 'custom:read-log', ->
  whatever.whatever.runShellCommand('uname -a; cat /tmp/y');
atom.commands.add 'atom-text-editor', 'custom:clean-up-mess', ->
  whatever.whatever.runShellCommand('rm /tmp/y');

Are there better ways to achieve the goal what I described?

What’s the easiest way to do something like this?


#2

You could use node’s child_process module.
Here is a little example:

child_process = require('child_process')
execAndPrintOutput = (cmd) ->
  child_process.exec cmd, (error, stdout, stderr) ->
    return atom.notifications.addError error.toString() if error
    atom.workspace.open().then (editor) ->
      editor.setText(stdout)
      if stderr.trim() isnt ''
        editor.insertText("\nSTDERR:\n#{stderr}")
      atom.views.getView(editor).scrollToBottom()

exec = (cmd) ->
  child_process.exec cmd, (error, stdout, stderr) ->
    return atom.notifications.addError error.toString() if error
    console.log "STDOUT of #{cmd}:\n#{stdout}" if stdout.trim() isnt ''
    console.error "STDERR of #{cmd}:\n#{stderr}" if stderr.trim() isnt ''

atom.commands.add 'atom-text-editor', 'custom:grep-and-alert', ->
  exec('grep -i err x > /tmp/y; notify-send "OK";')
atom.commands.add 'atom-text-editor', 'custom:read-log', ->
  execAndPrintOutput('uname -a; cat /tmp/y')
atom.commands.add 'atom-text-editor', 'custom:clean-up-mess', ->
  exec('rm /tmp/y')
  • Use exec if the command does not print anything useful. stdout and stderr are printed in Atom’s console (ctrl-shift-i) and you get a notification if the command fails.
  • Use execAndPrintOutput if you want to see the output in an untitled editor.

#3

If you’re willing to try another package then maybe take a look at process-palette. You can assign shortcut keys to commands and also add them to the command palette.


#4

This is exactly what I was looking for, thank you!


#5

Wow, process-palette seems really well done! It’s actually perfect for my use case, and the interface is really really nice.

I’m gonna use this one, although I’m glad that I learned something about hacking my own code in the init file.


#6

Awesome! I’m glad you find it useful :grinning: Feature request are welcome if you have any suggestions for improvements.