Skip to content

Instantly share code, notes, and snippets.

@labocho
Last active August 1, 2016 17:49
Show Gist options
  • Select an option

  • Save labocho/3d783c69b1bf383d34eb to your computer and use it in GitHub Desktop.

Select an option

Save labocho/3d783c69b1bf383d34eb to your computer and use it in GitHub Desktop.
New session (tab) in iTerm with(or without) command and name.
#!/usr/bin/env ruby
# Usage: iterm-new-session [-n NAME] [command]
# command should be quoted (e.g. iterm-new-session 'ls -l')
require "optparse"
require "open3"
require "json"
require "shellwords"
require "tmpdir"
def osascript(source, arg = {})
out, err, status = Open3.capture3("/usr/bin/osascript", "-l", "JavaScript", "-e", source, arg.to_json)
unless status.success?
$stderr.puts "osascript exited with #{status.to_i}"
$stderr.puts err
exit status.to_i
end
out
end
name = nil
OptionParser.new do |o|
o.on("-n NAME", "--name NAME"){|s| name = s }
o.order!(ARGV)
end
command = ARGV.first || ENV["SHELL"]
name ||= command.shellsplit.first.split("/").last
command = "cd #{Dir.pwd.shellescape} && " + command
script_filename = Dir.mktmpdir("iterm-new-session") + "/iterm-new-session.sh"
open(script_filename, "w"){|f| f.write(command) }
script = <<-JS
function run(argv) {
var options = JSON.parse(argv[0]);
var iTerm = Application("iTerm");
var terminal = iTerm.currentTerminal();
var session = new iTerm.Session();
terminal.sessions.push(session);
session.exec({command: options.command});
session.name = options.name;
}
JS
osascript(script, command: "/bin/sh #{script_filename.shellescape}", name: name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment