I am looking for a terminal command that will open a new tab in the current terminal that I am using. For example, I run the command in iTerm 2 and a new tab opens in iTerm2 because that is the terminal that i am using.
I know how to open a tab by naming a static application like so:
osascript -e 'tell application "iTerm" to activate' \
-e 'tell application "System Events" to tell process "iTerm" to keystroke "t" using command down'
But of course this still opens iTerm if I am doing something like calling the command from mac's Terminal. I would love to do something like below, but I am unsure how to get the name of the terminal I am using.
currentTerminal = getCurrentTerminalApplicationName()
osascript -e 'tell application "&{currentTerminal}" to activate' \
-e 'tell application "System Events" to tell process "&{currentTerminal}" to keystroke "t" using command down'
I am also open to other ideas.
While inside macOS terminal:
env | grep TERM
TERM_PROGRAM=Apple_Terminal
While inside iTerm2:
env | grep TERM
TERM_PROGRAM=iTerm.app
UPDATE
You can always do something like this:
#!/bin/bash
if [ "$TERM_PROGRAM" == "iTerm.app" ]; then
echo "iTerm2"
cat <<EOF >/tmp/file.py
import iterm2
async def main(connection):
app = await iterm2.async_get_app(connection)
window = app.current_terminal_window
if window is not None:
await window.async_create_tab()
else:
print("No current window")
iterm2.run_until_complete(main)
EOF
$HOME/Library/Application\ Support/iTerm2/iterm2env-3.10/versions/3.10.4/bin/python /tmp/file.py
else
echo "not iTerm2"
fi
This code will open new tab inside iTerm2 - otherwise, it will do nothing.
Related
I'd like to run a script to close all apps currently open in my doc. Figured out how to do with with the following script, where APPLICATIONNAME is the name of the app in the dock currently open
osascript -e 'quit app "APPLICATIONNAME"'
Any ideas on how to expand this command to encompass all apps open inside the doc?
Ideally we'd avoid using a killall flavor of script. As force closing running apps in bulk will pose risks in some circumstances
Firstly there is no terse solution to achieve this using osascript as described in your question. osascript by itself simply doesn't provide the options/arguments necessary to fulfil the logic of your requirement.
However, the following bash shell script (.sh) avoids using killall and will prompt the user to save any unsaved changes to document(s) before closing/quitting the application. (This is very similar to how the user is prompted to save any unsaved changes when shutting down the computer):
close-apps.sh
#!/bin/bash
# Creates a comma-separated String of open applications and assign it to the APPS variable.
APPS=$(osascript -e 'tell application "System Events" to get name of (processes where background only is false)')
# Convert the comma-separated String of open applications to an Array using IFS.
# http://stackoverflow.com/questions/10586153/split-string-into-an-array-in-bash
IFS=',' read -r -a myAppsArray <<< "$APPS"
# Loop through each item in the 'myAppsArray' Array.
for myApp in "${myAppsArray[#]}"
do
# Remove space character from the start of the Array item
appName=$(echo "$myApp" | sed 's/^ *//g')
# Avoid closing the "Finder" and your CLI tool.
# Note: you may need to change "iTerm" to "Terminal"
if [[ ! "$appName" == "Finder" && ! "$appName" == "iTerm" ]]; then
# quit the application
osascript -e 'quit app "'"$appName"'"'
fi
done
Note: In the following line of code we avoid closing the Finder and the CLI tool that the command will be run via. You will probably need to change "iTerm" to "Terminal", or to whatever the name of your CLI tool is:
if [[ ! "$appName" == "Finder" && ! "$appName" == "iTerm" ]]; then
Making close-apps.sh executable
As explained in this answer you will need to make the close-apps.sh executable before it can be run. To do this enter the following via your CLI:
$ chmod +x /path/to/close-apps.sh
(The /path/to/close-apps.sh part should be replaced with your path according to where the script is saved)
Running close-apps.sh via the CLI.
You run the shell script by entering the following into the CLI:
$ /path/to/close-apps.sh
(Again, the /path/to/close-apps.sh part should be replaced with your path according to where the script is saved)
Running close-apps.sh via an Applescript.
The shell script can also be executed via an AppleScript application simply by double-clicking instead of entering a command via the CLI.
To do this you'll need to:
Open the AppleScript Editor application, which can be found inside the Applications/Utilities/ folder.
Enter the following code:
on run
do shell script "/path/to/close-apps.sh"
quit
end run
(Again, the /path/to/close-apps.sh part should be replaced with your path according to where the .sh script is saved)
Save the Applescript and chose File Format: Application via the save dialog. Let's call it closeApps.app.
Finally, the following line of code in the close-apps.sh script should be changed from this:
if [[ ! "$appName" == "Finder" && ! "$appName" == "iTerm" ]]; then
... to this:
if [[ ! "$appName" == "Finder" && ! "$appName" == "closeApps" ]]; then
Note The filename of the Applescript (closeApps) replaces iTerm (or Terminal).
To close all applications open in the dock you simply double click the closeApps application icon.
Try this
tell application "System Events"
set appList to the name of every process whose background only is false
end tell
repeat with theApp in appList
try
tell application theApp to quit
end try
end repeat
I am creating a command line tool for my application.
It uses pkgbuild and productbuild to create the package. Its a launchdaemon binary.
I have preinstall and postinstall scripts.
After installation, may be in postinstall script, I need to detect if Firefox is running, then a prompt to the user that (s)he need to restart Firefox.
Is it possible to do that? How?
some excerpt from the script, its part of the postinstall script.
.........
## Check if Firefox is running in the background with no tab/window open.
function restart_empty_firefox (){
echo "Restarting firefox if no tab is opened. "
firefoxRunning=$(osascript \
-e 'tell application "System Events" to set fireFoxIsRunning to ((count of (name of every process where name is "Firefox")) > 0)' \
-e 'if fireFoxIsRunning then' \
-e 'set targetApp to "Firefox"' \
-e 'tell application targetApp to count (every window whose (closeable is true))' \
-e 'else' \
-e 'return 0' \
-e 'end if')
if [ $firefoxRunning -eq 0 ]; then
echo 'Firefox is in the background with no window and so quitting ...'
osascript -e 'quit app "Firefox"'
else
##### show a dialog to the user to restart Firefox
fi
}
firefox_update # not shown here
restart_empty_firefox
.............
You can use the process status (ps) tool:
ps aux | grep '[F]irefox.app' | awk '/firefox$/ {print $2}'
Result:
82480
This tells us that Firefox.app is indeed running (process 82480).
EDIT: Since you seem to be leaning in the direction of using an osascript here's an example which asks the user to relaunch Firefox (putting full control in their hands):
#!/bin/bash
osascript <<'END'
set theApp to "Firefox"
set theIcon to "Applications:Firefox.app:Contents:Resources:firefox.icns"
tell application "System Events"
if exists process theApp then
display dialog "Warning: Mozilla " & theApp & " should be closed." buttons {"Continue"} with icon file theIcon default button 1
if the button returned of the result is "Continue" then
end if
end if
display notification "Installation complete" with title "Application Package" subtitle "Please relaunch " & theApp
delay 3
end tell
END
If your script has sufficient privileges then using quit would be recommended over blatantly killing off the process. Ultimately that's how it should be done, otherwise just ask the user to please quit and relaunch Firefox themselves — problem solved.
osascript -e "set x to 3"
osascript -e "if x is 5 then"
osascript -e " tell application \"System Events\" to keystroke return"
osascript -e "end if"
The output i get
14:14: syntax error: Expected end of line but found end of script. (-2741)
0:6: syntax error: A “if” can’t go after this “end”. (-2740)
Can't see whats wrong with the script. Might be some issue with indentation. Anyone used osascript inside bash files ?
Put all your applescript lines together. This way:
osascript -e "set x to 3
if x is 5 then
tell application \"System Events\" to keystroke return
end if"
Additionally, you can create a file like the following with all your applescript code:
#!/usr/bin/osascript
set x to 3
if x is 5 then
tell application "System Events" to keystroke return
end if
I find this way easiest in respect of quoting and double-quoting and escaping, and using bash variables in the osascript:
#!/bin/bash
# Set bash variable to 3, then use it in osascript
count=3
osascript <<EOF
beep $count
tell application "Safari"
set theURL to URL of current tab of window 1
end tell
EOF
# Continue in bash
echo done
I have the following script:
i=1;
while [ $i -lt 51 ]
do
osascript -e 'tell app "Terminal"
do script "php $i.php"
end tell' &
i=$[$i+1]
done
I am trying to open a terminal window that executes 1 of 50 php scripts. However, I cannot get the value of $1 to print correctly. In fact, In each terminal its just blank. Each scripted is named 1.php to 50.php - how do I get the value of i to print properly to render the correct file name?
Note, I have been applescripting about an hour. Very open to suggestions to a better script. What I am trying to do is run 50 simultaneous PHP scripts in 50 separate windows simultaneously. Thanks!
It's just a quoting problem - change:
osascript -e 'tell app "Terminal"
do script "php $i.php"
end tell'
to:
osascript -e "tell app \"Terminal\"
do script \"php $i.php\"
end tell"
How do I use the terminal to open another terminal window but with a path I specify?
I am using automator to load my work stuff when I get to work, but I need to know how to do this:
Open Terminal and Type:
• cd Work/Company/Project/
• script/server
And then new tab in that terminal window and cd to the same folder.
This opens a new terminal window from a command prompt on Mac OSX , executes "cd /" and then keeps the window on top:
osascript -e 'tell application "terminal"' -e 'do script "cd /"' -e 'end tell'
You can put this into a script like this:
#!/bin/sh
osascript -e 'tell application "terminal"' -e "do script \"cd $1\"" -e 'end tell'
Hope this helps.
Use an applescript to do this.
e.g. Open Terminal Here
You can write a shell script to cd to that directory
So write a script that executes something like cd /user/music or something like that, save it as myscript.sh and run it using chmod +x myscript.sh.
This resource from the OS X developer network is pretty helpful
The two scripts below together handle the common scenarios:
1) If Terminal is already running, open a new terminal window and run the 'cd mydir' there
2) If terminal is not already running, use the initial window that Terminal spawns (window 0), rather than annoyingly launching a second window
NOTE: what's not quite perfect is if Terminal has several windows open, all of them will be brought to the front, overlapping any other apps. A solution to raising only the last terminal window to the front appears to require the black magic of AppleScriptObjC - references below:
https://apple.stackexchange.com/questions/39204/script-to-raise-a-single-window-to-the-front
http://tom.scogland.com/blog/2013/06/08/mac-raise-window-by-title/
Script 1 - open a text editor and save as:
/usr/local/bin/terminal-here.sh
#!/bin/sh
osascript `dirname $0`/terminal-here.scpt $1 > /dev/null 2> /dev/null
Script 2 - open 'AppleScript Editor', paste contents below and save as:
/usr/local/bin/terminal-here.scpt
# AppleScript to cd (change directory) to a path passed as an argument
# If Terminal.app is running, the script will open a new window and cd to the path
# If Terminal.app is NOT running, we'll use the window that Terminal opens automatically on launch
# Run script with passed arguments (if any)
on run argv
if (count of argv) > 0 then
# There was an argument passed so consider it to be the path
set mypath to item 1 of argv
else
# Since no argument was passed, default to the home directory
set mypath to "~"
end if
tell application "System Events"
if (count (processes whose bundle identifier is "com.apple.Terminal")) is 0 then
# Terminal isn't running so we'll make sure to run the 'cd' in Terminal's first window (0)
tell application "/Applications/Utilities/Terminal.app"
# Turn off echo, run the 'cd', clear screen, empty the scrollback, re-enable echo
do script "stty -echo; cd " & (mypath as text) & ";clear; printf \"\\e[3J\"; stty echo" in window 0
activate last window
end tell
else
# Terminal is already running so we'll let it open a new window for our 'cd' command
tell application "/Applications/Utilities/Terminal.app"
# Turn off echo, run the 'cd', clear screen, empty the scrollback, re-enable echo
do script "stty -echo; cd " & (mypath as text) & ";clear; printf \"\\e[3J\"; stty echo"
activate last window
end tell
end if
end tell
end run