Mac OS X: Bring (non-bundle) GUI applications to foreground when launched from the command line - macos

When a GUI process is launched from the OS X terminal, the window shows up in the background, and you have to use command-tab to give it focus.
Is there a way to make the terminal automatically give such GUIs focus after they are launched?
For example (assuming gitk is installed):
% gitk
should launch the GUI and then switch to it.
Note: For several reasons, using open as this answer suggests is not a general solution.
Update: To better explain why the open method isn't satisfactory, here's a sample bash session (with witty commentary).
% cd /my_repo
% gitk
Waiting for the GUI to appear ... any day now ... oh wait -- it's already open. I just didn't notice because it opened a window BEHIND my terminal. I wonder how long I was going to sit here waiting....
% open gitk
The file /my_repo/gitk does not exist.
Ah, of course.
% which gitk
/usr/bin/gitk
% open /usr/bin/gitk
What the ... it opened a new terminal window to run gitk, and it did so in my home directory, not /my_repo, so gitk complains that the current directory isn't actually a repository...

Do you need to invoke it synchronously? If not, you could start it asynchronously with & and then activate it with osascript -e 'tell application "gitk" to activate'.

If you are dealing with gitk specifically you can edit the gitk file to achieve this, I posted an answer on the apple stack exchange: https://apple.stackexchange.com/a/74917/35956
You can find the gitk file using the following command from the terminal
which gitk
In my gitk file I found a line that looks like the following near the top (line 3)
exec wish "$0" -- "$#"
I changed it to this
exec wish "$0" -- "$#" & exec osascript -e "tell application \"Wish\" to activate"
When I execute gitk from the command line the gitk window comes to the foreground, another side effect of this is that it executes asynchronously

You can wrap up #chris page's answer in a bash function and drop it in your .bashrc
function gitk() {
command gitk "$#"&
command osascript -e "delay .5" -e "tell application \"wish\" to activate"
}
There should be a way to get rid of the delay by looping and looking for 'wish' with a timeout.
NOTE: 'Wish' is the window title that shows up on my Mac for gitk.

Related

Why does Fastscripts work with this but Platypus doesn't

Mac running Catalina. This code
#!/bin/bash
pbpaste|pbcopy
pbpaste>/tmp/tmp$$
open -W -a macvim /tmp/tmp$$
while [ `ps -A|grep MacVim|wc -l` -gt 1 ]
do sleep 1
done
cat /tmp/tmp$$|pbcopy
rm -f /tmp/tmp$$
is intended to plain-text the paste buffer then call up a terminal running macvim so I can use vi with less faff then put the result back in the clipboard. Its a way to speed-up editing when using various tools other tools and I just want to edit a section with vi.
I works well when called from Fastscripts or just plain execution but it won't work when I use Platypus to build a menubar app so its one fast click to use it - or rather, it works sometimes. Sometimes it hangs because it cannot connect input to the window in which macvim runs. I have to kill it from Activity Monitor to regain any control of input to other windows such as terminal. I've tried connecting stdin in the "open" command but still only works sometimes. And it shouldn't be standin anyway.
How is Fastscripts launching it and how can I do the same inside the script ?
I'd like very much to be able to launch it with a single click from the menubar but I don't know how to. I can build the platypus app if I know what to put in the shell script.
Thanks
andy

AppleScript: execution error -10810 when launching certain applications from shebang'ed scripts

I'm running OS X 10.10.2. I'm facing a weird issue where AppleScript won't launch applications from shebang'ed scripts while working fine everywhere else (Script Editor, piping to osascript, etc.). Specifically, consider the following example script named launch-app:
#!/usr/bin/osascript
launch application "TextEdit"
When TextEdit is not running and I do
./launch-app
I get
./launch-app:0:29: execution error: An error of type -10810 has occurred. (-10810)
When I do
<launch-app osascript
Well, it works just fine; which means the following Bash script will also work:
#!/usr/bin/env bash
osascript <<EOF
launch application "TextEdit"
EOF
Really weird. (By the way, a tell ... activate ... end tell block results in the same error. I'm using launch here just to keep to example minimal.)
I have some old scripts that involve activating an application (well, practically all my old scripts involve tell ... activate ... end tell) that definitely worked in the past. I can't tell when things began to fall apart because when I run those scripts, most often the applications to activate are already launched. I have the impression that the issue dates back at least to 10.10.1.
I have looked at several related posts here on SO, e.g., this one, but they don't help. I also tried to understand error -10810 by reading articles like this one, but my problem definitely doesn't look like a filled process table (otherwise why does directly calling osascript works while running osascript from a shebang doesn't?).
Update: The bug has been fixed in OSX 10.10.3.
Just to provide a state-of-the-union post:
The behavior observed is a bug in OSX 10.10 still unresolved as of OSX 10.10.2 (as of 10 Mar 2015):
Anyone interested in getting this fixed should file their own bug at http://bugreport.apple.com.
It applies to executable scripts that are directly or indirectly passed to osascript - whether:
explicitly (osascript launch-app)
or implicitly, via the shebang line, by direct invocation (./launch-app)
The specific form of the shebang line is irrelevant (whether #!/usr/bin/osascript or #!/usr/bin/env osascript or #!/usr/bin/env osascript -l JavaScript or ...), what matters is whether the file has the executable bit (permission) set (e.g., via chmod +x).
Workarounds:
As suggested by the OP, feed the file to osascript via stdin: osascript < launch-app
This has side effects; for instance, name of me will report msng instead of the name of the script.
Remove the executable bit from the script and invoke it explicitly with osascript:
chmod -x launch-app # a one-time operation
osascript launch-app # with the executable bit unset, this should work
Looking at the man page for osascript, when you send lines of applescript code you should put the "-e" option infront of each separate line.
So here's what I tested. I made a bash script with the -e option...
#!/bin/bash
osascript -e 'launch application "TextEdit"'
And one without.
#!/bin/bash
osascript 'launch application "TextEdit"'
The one without the -e option does not run. As such I think this could be a cause of your problem... there's no -e option in your code.
Note that I tested your code too and got the same error as you. There's a command line utility "/usr/bin/macerror" and I entered your error code into that. Here's the result.
Unknown error (-10810) at /usr/bin/macerror5.18 line 40, <DATA> line 1.
Good luck.
There is no need for using osascript to launch applications. There is a built in command line utility named open, that will open your app from the terminal commandline, or a shebanged script. For doucumentation, enter "man open" in a terminal window. It is a really nifty utility, with a lot of options. :)
The open utility, will lauch applications that are not running, but I also wonder out of curiosity: have you tried "tell application appname to run", or just "tell application appname to activate"?
The osascript below, works for me, on 10.9
#!/usr/bin/osascript
tell application "TextEdit" to launch
I guess you'll have to commmand the app to do something, and not just try to "launch" it. Maybe "tell me to launch application appname also works".
Edit
I prefer to use open -b "com.apple.textedit", because then I also get the front window of textEdit, brought to front.
By the way, with the open -e command, you can open a textfile directly into TextEdit from the commandline. open is not totally as good as the plumb utility of plan-9, but it is really nifty.

Cannot open multiple files with Emacs on Mac

I can open a single file with Emacs, no problem. But I'm used to Emacs on Linux, where typing emacs test.cpp & would open a new Emacs frame, leaving the terminal free. On OS X, however, when I try to open a new frame with emacs test.cpp &, the terminal shows a process was created but the window fails to pop up. If I push Ctrl+C, the terminal shows "Stopped", but I see the process is still running because I can see it in the task monitor.
How to solve this problem? Thanks!
The issue here is that the command emacs on Linux is generally just the Emacs binary itself, which opens a new frame (that's Emacs-speak for X11 or other GUI window) unless you specify -nw on the command line; in contrast, the emacs command provided by Homebrew is a shell script that calls /usr/local/Cellar/emacs/24.3/Emacs.app/Contents/MacOS/Emacs -nw "$#" (substituting the version installed for 24.3). So the Homebrew version launches as a terminal app.
You can make a shell script that just runs /usr/local/Cellar/emacs/24.3/Emacs.app/Contents/MacOS/Emacs "$#", and it would behave somewhat as you expect, except that you would be launching a brand-new instance of the Mac app, which would cause an additional Emacs icon to appear on the Dock. Such a thing isn't considered "Mac-like," but it's not the end of the world.
An alternate solution, which is used a lot across different operating systems, is to make one Emacs process a server and then use emacsclient to open files from the command line. Emacsclient can open files in the current terminal, a new frame (GUI window), or an existing instance of Emacs. For an instance of Emacs to run as a server just requires that you run M-x server-start within it, or put (server-start) inside your init file (~/.emacs or ~/.emacs.d/init.el).
My Emacs config has this snippet, which starts server mode automatically when I launch the GUI app:
(when (display-graphic-p)
(server-start))
Then, once Emacs is running (you can make it autostart upon login in System Preferences > Users & Groups > Login Items), type emacsclient -nw test.cpp to open the file in the terminal, or emacsclient test.cpp & to open it in an existing frame, or emacsclient -c test.cpp & to open a new frame. (Note that if you open it in an existing frame, you use C-x # to close the buffer without closing the frame, as opposed to C-x C-c.)
Note that the terminal emacsclient command I gave just now didn't use & but the GUI ones did. & at the end of a command line puts the process in the background, meaning it's not monopolizing your terminal. For whatever reason (probably because it wouldn't be sensible to have a full-screen terminal app running in the background), when you invoke the terminal version of Emacs with &, it just suspends itself. The same thing would happen if you pressed C-z within Emacs. To get it back into the foreground, type fg (actually you can have multiple background processes, in which case fg would just pick the most recent one unless you specified a job specifier; see bash's man page (man bash) and search for JOB CONTROL if you're interested in the details).

How do I get a Mac ".command" file to automatically quit after running a shell script?

In my shell script, my last lines are:
...
echo "$l" done
done
exit
I have Terminal preference set to "When the shell exits: Close the window". In all other cases, when I type "exit" or "logout", in Terminal, the window closes, but for this ".command" file (I can double-click on my shell script file, and the script runs), instead of closing the window, while the file's code says "exit", what shows on the screen is:
...
$l done
logout
[Process completed]
...and the window remains open. Does anyone know how to get a shell script to run, and then just automatically quit the Terminal window on completion?
Thanks!
I was finally able to track down an answer to this. Similar to cobbal's answer, it invokes AppleScript, but since it's the only window that I'd have open, and I want to run my script as a quick open-and-close operation, this more brutish approach, works great for me.
Within the ".command" script itself, "...add this line to your script at the end"
osascript -e 'tell application "Terminal" to quit' &
exit
SOURCE: http://forums.macosxhints.com/archive/index.php/t-2538.html
This worked perfectly for me.. it just closes that execution window leaving other terminal windows open
Just open Terminal and go to Terminal > Preferences > Settings > Shell: > When the shell exits: -> Close if the shell exited cleanly
Then just add exit; at the end of your file.
Use the 'Terminal > Preferences > Settings > Shell: > When the shell exits: -> Close if the shell exited cleanly' option mentioned above, but put
exit 0
as the last line of your command file. That ensures the script really does 'exit cleanly' - otherwise if the previous command doesn't return success then the window won't close.
Short of having to use the AppleScript solutions above, this is the only shell script solution that worked (exit didn't), even if abruptly, for me (tested in OS X 10.9):
...
echo "$l" done
done
killall Terminal
Of course this will kill all running Terminal instances, so if you were working on a Terminal window before launching the script, it will be terminated as well. Luckily, relaunching Terminal gets you to a "Restored" state but, nevertheless, this must be considered only for edge cases and not as a clean solution.
There is a setting for this in the Terminal application. Unfortunately, it is relative to all Terminal windows, not only those launched via .command file.
you could use some applescript hacking for this:
tell application "Terminal"
repeat with i from 1 to number of windows
if (number of (tabs of (item i of windows) whose tty is "/dev/ttys002")) is not 0 then
close item i of windows
exit repeat
end if
end repeat
end tell
replacing /dev/ttys002 with your tty
I'm using the following command in my script
quit -n terminal
Of course you have to have the terminal set to never prompt before closing.

Linux equivalent of the DOS "start" command?

I'm writing a ksh script and I have to run a executable at a separate Command Prompt window.
xdg-open is a similar command line app in linux.
see https://superuser.com/questions/38984/linux-equivalent-command-for-open-command-on-mac-windows for details on its use.
I believe you mean something like xterm -e your.sh &
Don't forget the final &
maybe it´s not a seperate window that gets started, but you can run some executables in background using "&"
e.g.
./myexecutable &
means your script will not wait until myexecutable has finished but goes on immediately. maybe this is what you are looking for.
regards
xdg-open is a good equivalent for the MS windows commandline start command:
xdg-open file
opens that file or url with its default application
xdg-open .
opens the currect folder in the default file manager
One of the most useful terminal session programs is screen.
screen -dmS title executable
You can list all your screen sessions by running
screen -ls
And you can connect to your created screen session (also allowing multiple simultaneous/synchronized sessions) by running
screen -x title
This will open up the emulated terminal in the current window where executable is running. You can detach a screen session by pressing C-a C-d, and can reattach as many times as you wish.
If you really want your program started in a new terminal window, you could do something like this:
xterm yourtextmodeprogram
or
gnome-terminal -e yourtextmodeprogram
or
konsole -e mc
Trouble is that you cannot count on a particular terminal emulator being installed, so (again: if you really want to do this) you would need to look for the common ones and then execute the first one encountered.
As Joachim mentioned: The normal way to do this is to background the command (read about shell job control somewhere, if you want to dig deeper).
There are also cases where you want to start a persistent shell, i.e. a shell session which lives on when you close the terminal window. There are two ways to do this:
batch-oriented: nohup command-to-run &
interactive: screen
if you want a new windows, just start a new instance of your terminal application: in kde it's
konsole -e whatever
i'm sure the Gnome terminal has similar options
Some have recommended starting it in the background with &, but beware that that will still send all console output from the application you launch to the terminal you launched it from. Additionally, if you close the initial terminal the program you loaded will end.
If you're using a desktop environment like KDE or GNOME, I'd check the alt+f2 launching apps (gnome-open is the one for GNOME, I don't know the name of the KDE app) and see if you can pass them the command to launch as an argument.
Also, if your intention is to launch a daemon, you should check the nohup documentation.
I used nohup as the following command and it works:
nohup <your command> &
then press enter and enter!
don't forget the last &
for example, I ran a python code listening to port 5000:
nohup python3 -W ignore mycode.py &
then I made sure of running by netstat -tulnp | grep :5000 and it was ok.

Resources