AppleScript Terminal

[Terminal] python3 pip のアップデートとパッケージのアップデート


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

###インストールするパッケージ
set listPackage to {"pip", "pypdf", "pypdf", "pdfautonup", "setuptools-scm", "stdeb", "PyPDF2", "PyPDF3", "pdfnup"} as list


try
do shell script "/usr/bin/xcode-select --install"
end try
##
try
  set strCmdText to ("/bin/mkdir -p $HOME/bin") as text
do shell script strCmdText
  set strCmdText to ("/bin/chmod 700 $HOME/Library/Caches/pip") as text
do shell script strCmdText
end try
##
try
  set strCmdText to ("/bin/mkdir -p $HOME/Library/Caches/pip") as text
do shell script strCmdText
  set strCmdText to ("/bin/chmod 777 $HOME/Library/Caches/pip") as text
do shell script strCmdText
end try
##
try
  set strCmdText to ("/bin/mkdir -p $HOME/Library/Python/3.9/lib/python/site-packages") as text
do shell script strCmdText
  set strCmdText to ("/bin/chmod 755 $HOME/Library/Python/3.9/lib/python/site-packages") as text
do shell script strCmdText
end try



## python3のパスチェック
try
  set strCmdText to ("/usr/bin/which python3") as text
  set strResponse to (do shell script strCmdText) as text
on error
return "python3が見つかりませんでした終了します"
end try
########################
#install
repeat with itemPackage in listPackage
  set strPackageName to itemPackage as text
  tell application "Terminal"
    set strCmdText to ("\"" & strResponse & "\" -m pip install --user \"" & strPackageName & "\"") as text
do script strCmdText
activate
  end tell
  
  repeat 5 times
    tell application "Terminal"
      set numCntWindow to (count of every window) as integer
      if numCntWindow = 1 then
log "Windowがありません"
        exit repeat
      end if
      tell front window
        set numWindowID to id
        tell front tab
          set boolBusy to busy as boolean
        end tell
      end tell
    end tell
    if boolBusy is false then
log "処理していないので閉じる"
      tell application "Terminal"
do script "\n\n" in window id numWindowID
do script "exit" in window id numWindowID
delay 1
close front window saving no
      end tell
      exit repeat
    else
log "busyなので1秒まつ"
delay 1
    end if
  end repeat
  tell application "Terminal"
    set numCntWindow to (count of every window) as integer
  end tell
  if numCntWindow = 1 then
log "Windowがありません"
  else
    ###
    tell application "Terminal"
      tell front window
        set numWindowID to id
        tell front tab
          set boolBusy to busy as boolean
        end tell
      end tell
    end tell
    if boolBusy is true then
      tell application "System Events"
        tell application "Terminal" to activate
keystroke "c" using {control down}
      end tell
      tell application "Terminal"
do script "\n\n" in window id numWindowID
do script "exit" in window id numWindowID
delay 1
close front window saving no
      end tell
    end if
  end if
end repeat
########################
#upgrade
repeat with itemPackage in listPackage
  set strPackageName to itemPackage as text
  tell application "Terminal"
    set strCmdText to ("\"" & strResponse & "\" -m pip install --upgrade --user \"" & strPackageName & "\"") as text
do script strCmdText
activate
  end tell
  
  repeat 5 times
    tell application "Terminal"
      set numCntWindow to (count of every window) as integer
      if numCntWindow = 1 then
log "Windowがありません"
        exit repeat
      end if
      tell front window
        set numWindowID to id
        tell front tab
          set boolBusy to busy as boolean
        end tell
      end tell
    end tell
    if boolBusy is false then
log "処理していないので閉じる"
      tell application "Terminal"
do script "\n\n" in window id numWindowID
do script "exit" in window id numWindowID
delay 1
close front window saving no
      end tell
      exit repeat
    else
log "busyなので1秒まつ"
delay 1
    end if
  end repeat
  tell application "Terminal"
    set numCntWindow to (count of every window) as integer
  end tell
  if numCntWindow = 1 then
log "Windowがありません"
  else
    ###
    tell application "Terminal"
      tell front window
        set numWindowID to id
        tell front tab
          set boolBusy to busy as boolean
        end tell
      end tell
    end tell
    if boolBusy is true then
      tell application "System Events"
        tell application "Terminal" to activate
keystroke "c" using {control down}
      end tell
      tell application "Terminal"
do script "\n\n" in window id numWindowID
do script "exit" in window id numWindowID
delay 1
close front window saving no
      end tell
    end if
  end if
end repeat


display notification "処理終了" with title "処理が終了" subtitle "処理が終了しました" sound name "Sonumi"
return


|

[Terminal]コマンド実行後指定秒数で終了し閉じる


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

##最大待ち時間 秒
set numMaxRepeatTime to 5 as integer

###実行するコマンド
tell application "Terminal"
activate
do script "/sbin/ping www.yahoo.co.jp"
end tell
delay 2


###くりかえし
repeat numMaxRepeatTime times
  tell application "Terminal"
    ##Windowの数を数えて
    set numCntWindow to (count of every window) as integer
    if numCntWindow = 1 then
log "Windowがありません"
      exit repeat
    end if
    tell front window
      ##WindowIDを取得
      set numWindowID to id
      tell front tab
        ##コマンド実行中か?
        set boolBusy to busy as boolean
      end tell
    end tell
  end tell
  ##終了しているなら
  if boolBusy is false then
log "処理していないので閉じる"
    tell application "Terminal"
do script "\n\n" in window id numWindowID
do script "exit" in window id numWindowID
delay 1
close front window saving no
    end tell
    exit repeat
    ##コマンド実行中なら
  else
log "busyなので1秒まつ"
delay 1
  end if
end repeat
###くりかえしを抜けたあとで
tell application "Terminal"
  tell front window
    set numWindowID to id
    tell front tab
      ##今一度実行中か?確認して
      set boolBusy to busy as boolean
    end tell
  end tell
end tell
###実行中ならCTL+Cを送って中断させて
if boolBusy is true then
  tell application "System Events"
    tell application "Terminal" to activate
keystroke "c" using {control down}
  end tell
  ##Windowを閉じる
  tell application "Terminal"
do script "\n\n" in window id numWindowID
do script "exit" in window id numWindowID
delay 1
close front window saving no
  end tell
  
end if



return


|

[Terminal]ウィンドウ設定が常にタブの場合も新規ウィンドウを開く


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKIt"
use framework "UniformTypeIdentifiers"
use scripting additions

set strBundleID to "com.apple.Terminal"

###起動はランチを使うと新規ウィンドウが出来ない
tell application "Terminal" to launch
###ウィンドウの数を数えて
tell application "Terminal"
  activate
  set numCntWindow to (count of every window) as integer
end tell
###ウィンドウが無いなら終了する
if numCntWindow = 0 then
  tell application "Terminal" to quit
  delay 2
  tell application "Terminal" to launch
end if
####新規ウィンドウを開く(SystemEvent方式)
tell application "Terminal"
  activate
  tell application "System Events"
    tell process "Terminal"
      set frontmost to true
key down {command}
      keystroke "n"
key up {command}
    end tell
  end tell
end tell
###システムイベントの場合ウィンドウが出来るのを待つ
repeat 5 times
  tell application "Terminal"
    set numCntWindow to (count of every window) as integer
  end tell
  if numCntWindow = 0 then
    delay 0.5
  else
    exit repeat
  end if
end repeat

tell application "Terminal"
  tell front window
    set numWindowID to id as integer
  end tell
  tell window id numWindowID
    set position to {0, 25}
  end tell
end tell
###新規ウィンドウを開く(do script方式)
tell application "Terminal"
  launch
  activate
  set objTabWindows to do script "\n"
  tell objTabWindows
    activate
  end tell
end tell
####新規ウィンドウを開く
tell application "Terminal"
  activate
  tell application "System Events"
    tell process "Terminal"
      set frontmost to true
click menu item "タブを新しいウインドウに移動" of menu 1 of menu bar item "ウインドウ" of menu bar 1
    end tell
  end tell
  tell front window
    set numWindowID to id as integer
  end tell
  tell window id numWindowID
    set position to {0, 340}
  end tell
end tell

|

[Terminal]起動方法によるウィンドウ生成の違い


【スクリプトエディタで開く】|

tell application "Terminal" to launch
-->新規ウィンドウが出来ない
tell application "Terminal" to activate
-->新規ウィンドウが出来る

|

[zsh_sessions]セッションファイルを起動時に削除


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use scripting additions

property refMe : a reference to current application


###ディレクトリ
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidTempDirURL to appFileManager's temporaryDirectory()
###ひとつ階層上
set ocidContainerDirPathURL to ocidTempDirURL's URLByDeletingLastPathComponent()
set ocidCleanupDirPathURL to ocidContainerDirPathURL's URLByAppendingPathComponent:("Cleanup At Startup")
##起動時に削除するフォルダを作成
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
# 777-->511 755-->493 700-->448 766-->502
ocidAttrDict's setValue:(511) forKey:(refMe's NSFilePosixPermissions)
set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidCleanupDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)
#####zsh_sessionsのパス
set ocidHomeDirURL to appFileManager's homeDirectoryForCurrentUser()
set ocidSessionsDirPathURL to ocidHomeDirURL's URLByAppendingPathComponent:(".zsh_sessions")
set strSessionsDirPath to (ocidSessionsDirPathURL's |path|()) as text
####コマンド整形
set strCommandText to ("/usr/bin/touch \"" & strSessionsDirPath & "\"")
set ocidCommandText to refMe's NSString's stringWithString:(strCommandText)
set ocidTermTask to refMe's NSTask's alloc()'s init()
ocidTermTask's setLaunchPath:"/bin/zsh"
ocidTermTask's setArguments:({"-c", ocidCommandText})
set listDoneReturn to ocidTermTask's launchAndReturnError:(reference)
###現在のzsh_sessionsをゴミ箱に
set listResult to (appFileManager's trashItemAtURL:(ocidSessionsDirPathURL) resultingItemURL:(missing value) |error|:(reference))
###起動時に削除する項目にシンボリックリンクを作成する
set listResult to appFileManager's createSymbolicLinkAtURL:(ocidSessionsDirPathURL) withDestinationURL:(ocidCleanupDirPathURL) |error|:(reference)

return

|

ターミナル出力をテキストファイルに


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#com.cocolog-nifty.quicktimer.icefloe
(* Base Script
https://www.macscripter.net/t/lets-say-you-like-to-copy-text-from-terminal-app/74984
*)
#
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions
property refMe : a reference to current application

###ファイル名
set strDateNo to doGetDateNo("yyyyMMddhhmmss")
set strFileName to "ターミナル出力." & strDateNo & ".txt"


###デスクトップフォルダ に保存
set appFileManager to refMe's NSFileManager's defaultManager()
set listResponse to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidUserDesktopPathURL to (item 1 of listResponse)
###ファイルパスURL
set ocidSaveFilePathURL to ocidUserDesktopPathURL's URLByAppendingPathComponent:(strFileName) isDirectory:false
set ocidSaveFilePath to ocidSaveFilePathURL's |path|()
set strSaveFilePath to ocidSaveFilePath as text
###本処理
set strText to its doGetAttributesOfProcess("Terminal")
###戻り値をテキストエディタに展開
tell application "TextEdit"
  make new document with properties {name:strFileName, path:strSaveFilePath, text:strText}
  tell document strFileName
    activate
    ###保存して初めて確定
save in (POSIX file strSaveFilePath)
close
  end tell
  open (POSIX file strSaveFilePath)
  activate
end tell







on doGetAttributesOfProcess(argProcessName)
  tell application "System Events"
    set listAttributeName to name of attributes of process argProcessName
    
    repeat with itemAttribute in listAttributeName
      tell (attribute itemAttribute of process argProcessName)
log its value as list
log itemAttribute
      end tell
    end repeat
    
    if "AXFocusedUIElement" is in listAttributeName then
      tell value of attribute "AXFocusedUIElement" of process argProcessName
return its value
      end tell
    end if
  end tell
end doGetAttributesOfProcess





to doGetDateNo(strDateFormat)
  ####日付情報の取得
  set ocidDate to current application's NSDate's |date|()
  ###日付のフォーマットを定義
  set ocidNSDateFormatter to current application's NSDateFormatter's alloc()'s init()
ocidNSDateFormatter's setLocale:(current application's NSLocale's localeWithLocaleIdentifier:"ja_JP_POSIX")
ocidNSDateFormatter's setDateFormat:strDateFormat
  set ocidDateAndTime to ocidNSDateFormatter's stringFromDate:ocidDate
  set strDateAndTime to ocidDateAndTime as text
return strDateAndTime
end doGetDateNo


|

ManページをPDFに その2


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
# Base script
# https://scriptingosx.com/2022/11/on-viewing-man-pages-ventura-update/
#
#com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use scripting additions

property refMe : a reference to current application


##############################
#####ダイアログを前面に
##############################
tell current application
  set strName to name as text
end tell
###スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
##############################
#####クリップボードの内容取得
##############################
set ocidPasteboard to refMe's NSPasteboard's generalPasteboard()
set ocidPastBoardTypeArray to ocidPasteboard's types
set boolContain to ocidPastBoardTypeArray's containsObject:"public.utf8-plain-text"
if boolContain = true then
  set strReadString to (the clipboard as text)
else
  set boolContain to ocidPastBoardTypeArray's containsObject:"NSStringPboardType"
  if boolContain = true then
    set ocidReadString to ocidPasteboard's readObjectsForClasses:({refMe's NSString}) options:(missing value)
    set strReadString to ocidReadString as text
  else
    log "テキストなし"
    set strReadString to "COMMAND" as text
  end if
end if
set aliasIconPath to (POSIX file "/System/Applications/Utilities/Terminal.app/Contents/Resources/Terminal.icns") as alias
try
  set objResponse to (display dialog "コマンド名を入力してください" with title "入力してください" default answer strReadString buttons {"OK", "キャンセル"} default button "OK" cancel button "キャンセル" with icon aliasIconPath giving up after 10 without hidden answer)
on error
  log "エラーしました"
return "エラーしました"
  error number -128
end try
if true is equal to (gave up of objResponse) then
return "時間切れですやりなおしてください"
  error number -128
end if
if "OK" is equal to (button returned of objResponse) then
  set theResponse to (text returned of objResponse) as text
else
  log "エラーしました"
return "エラーしました"
  error number -128
end if

##############################
## Save PS dir URL
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidTempDirURL to appFileManager's temporaryDirectory()
set ocidUUID to refMe's NSUUID's alloc()'s init()
set ocidUUIDString to ocidUUID's UUIDString
set ocidSaveDirPathURL to ocidTempDirURL's URLByAppendingPathComponent:(ocidUUIDString) isDirectory:true
### Make SaveDir
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
ocidAttrDict's setValue:(511) forKey:(refMe's NSFilePosixPermissions)
set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)
###Save PS
set strFileName to (theResponse & ".pdf") as text
set ocidPdfFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strFileName) isDirectory:false
set strPdfFilePath to ocidPdfFilePathURL's |path|() as text

##############################
## PS書き出して
set strCommandText to ("/usr/bin/mandoc -T pdf \"$(/usr/bin/man -w " & theResponse & ")\" > \"" & strPdfFilePath & "\"") as text
do shell script strCommandText

##プレビューで開く
set aliasPdfFilePath to (ocidPdfFilePathURL's absoluteURL()) as alias
tell application id "com.apple.Preview"
  activate
  set numWindow to count of window
  if numWindow = 0 then
    try
open file aliasPdfFilePath
    on error
      log "ここでエラー"
    end try
  else
open file aliasPdfFilePath
  end if
end tell

|

ManページをPDFに その1


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
# Acrobat PPD は
# https://quicktimer.cocolog-nifty.com/icefloe/2023/05/post-3e373c.html
# からどうぞ
#com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use scripting additions

property refMe : a reference to current application

set strPPDsFilePath to ("/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/PrintCore.framework/Versions/A/Resources/Generic.ppd") as text

## set strPPDsFilePath to ("/Users/Shared/Library/Printers/PPDs/Contents/Resources/Acrobat/ADPDF9J.PPD") as text


##############################
#####ダイアログを前面に
##############################
tell current application
  set strName to name as text
end tell
###スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
##############################
#####クリップボードの内容取得
##############################
set ocidPasteboard to refMe's NSPasteboard's generalPasteboard()
set ocidPastBoardTypeArray to ocidPasteboard's types
set boolContain to ocidPastBoardTypeArray's containsObject:"public.utf8-plain-text"
if boolContain = true then
  set strReadString to (the clipboard as text)
else
  set boolContain to ocidPastBoardTypeArray's containsObject:"NSStringPboardType"
  if boolContain = true then
    set ocidReadString to ocidPasteboard's readObjectsForClasses:({refMe's NSString}) options:(missing value)
    set strReadString to ocidReadString as text
  else
    log "テキストなし"
    set strReadString to "COMMAND" as text
  end if
end if
set aliasIconPath to (POSIX file "/System/Applications/Utilities/Terminal.app/Contents/Resources/Terminal.icns") as alias
try
  set objResponse to (display dialog "コマンド名を入力してください" with title "入力してください" default answer strReadString buttons {"OK", "キャンセル"} default button "OK" cancel button "キャンセル" with icon aliasIconPath giving up after 10 without hidden answer)
on error
  log "エラーしました"
return "エラーしました"
  error number -128
end try
if true is equal to (gave up of objResponse) then
return "時間切れですやりなおしてください"
  error number -128
end if
if "OK" is equal to (button returned of objResponse) then
  set theResponse to (text returned of objResponse) as text
else
  log "エラーしました"
return "エラーしました"
  error number -128
end if

##############################
## Save PS dir URL
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidTempDirURL to appFileManager's temporaryDirectory()
set ocidUUID to refMe's NSUUID's alloc()'s init()
set ocidUUIDString to ocidUUID's UUIDString
set ocidSaveDirPathURL to ocidTempDirURL's URLByAppendingPathComponent:(ocidUUIDString) isDirectory:true
### Make SaveDir
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
ocidAttrDict's setValue:(511) forKey:(refMe's NSFilePosixPermissions)
set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)
###Save PS
set strFileName to (theResponse & ".ps") as text
set ocidPsFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strFileName) isDirectory:false
set strPsFilePath to ocidPsFilePathURL's |path|() as text

##############################
## PS書き出して
set strCommandText to ("/usr/bin/man -t " & theResponse & " > \"" & strPsFilePath & "\"") as text
do shell script strCommandText

##############################
##PDF にする
####出力ファイル名
set strPdfFileName to (theResponse & ".pdf") as text
###デスクトップ
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidDesktopDirURL to ocidURLsArray's firstObject()
set strDesktopDirPath to ocidDesktopDirURL's |path|() as text
set ocidPdfFilePathURL to ocidDesktopDirURL's URLByAppendingPathComponent:(strPdfFileName)
###存在チェック
set boolFileExist to (ocidPdfFilePathURL's checkResourceIsReachableAndReturnError:(missing value)) as boolean
if boolFileExist is true then
  ####日付情報の取得
  set ocidDate to refMe's NSDate's |date|()
  ###日付のフォーマットを定義
  set ocidNSDateFormatter to refMe's NSDateFormatter's alloc()'s init()
(ocidNSDateFormatter's setDateFormat:"yyyyMMdd-hhmm")
  set ocidDateAndTime to (ocidNSDateFormatter's stringFromDate:(ocidDate))
  set strDateAndTime to ocidDateAndTime as text
  ####ファイル名に日付を入れる
  set strPdfFilePath to (strDesktopDirPath & "/" & strPdfFileName & "." & strDateAndTime & ".pdf") as text
else
  ####出力ファイルパス
  set strPdfFilePath to (strDesktopDirPath & "/" & strPdfFileName & "") as text
end if

################################################
####コマンドパス
set strBinPath to "/usr/sbin/cupsfilter"
#####コマンド整形
set strCommandText to ("\"" & strBinPath & "\" -f \"" & strPsFilePath & "\" -m \"application/pdf\" -p \"" & strPPDsFilePath & "\" -e -t \"" & theResponse & "\" > \"" & strPdfFilePath & "\"")
####ターミナルで開く
tell application "Terminal"
  launch
  activate
  set objWindowID to (do script "\n\n")
  delay 1
do script strCommandText in objWindowID
end tell

|

[Terminal]コマンド実行後に閉じる(control Cを追加)


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use scripting additions

property refMe : a reference to current application

##############################
#####ダイアログを前面に
##############################
tell current application
  set strName to name as text
end tell
###スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
##############################
#####クリップボードの内容取得
##############################
set ocidPasteboard to refMe's NSPasteboard's generalPasteboard()
set ocidPastBoardTypeArray to ocidPasteboard's types
set boolContain to ocidPastBoardTypeArray's containsObject:"public.utf8-plain-text"
if boolContain = true then
  set strReadString to (the clipboard as text)
else
  set boolContain to ocidPastBoardTypeArray's containsObject:"NSStringPboardType"
  if boolContain = true then
    set ocidReadString to ocidPasteboard's readObjectsForClasses:({refMe's NSString}) options:(missing value)
    set strReadString to ocidReadString as text
  else
    log "テキストなし"
    set strReadString to "COMMANDを入力" as text
  end if
end if
set aliasIconPath to (POSIX file "/System/Applications/Utilities/Terminal.app/Contents/Resources/Terminal.icns") as alias
try
  set objResponse to (display dialog "入力したコマンドをターミナルで実行します" with title "入力してください" default answer strReadString buttons {"OK", "キャンセル"} default button "OK" cancel button "キャンセル" with icon aliasIconPath giving up after 120 without hidden answer)
on error
  log "エラーしました"
return "エラーしました"
  error number -128
end try
if true is equal to (gave up of objResponse) then
return "時間切れですやりなおしてください"
  error number -128
end if
if "OK" is equal to (button returned of objResponse) then
  set theResponse to (text returned of objResponse) as text
else
  log "エラーしました"
return "エラーしました"
  error number -128
end if
##############################
## 実行するコマンド
set strCommandText to theResponse as text
##############################
tell application "Terminal" to activate
delay 0.2
## 実行中チェック
tell application "Terminal"
  set numCntWindow to (count of every window) as integer
end tell
delay 0.5
if numCntWindow = 0 then
  log "Windowないので新規で作る"
  tell application "Terminal"
    set objNewWindow to (do script "\n")
  end tell
else
  log "Windowがある場合は、何か実行中か?をチェック"
  tell application "Terminal"
    tell front window
      tell front tab
set boolTabStatus to busy as boolean
set listProcess to processes as list
      end tell
    end tell
    set objNewWindow to selected tab of front window
  end tell
  ###前面のタブがbusy=実行中なら新規Window作る
  if boolTabStatus = true then
    tell application "Terminal"
      set objNewWindow to (do script "\n")
    end tell
    ###前面のタブにプロセスが無い場合=exit済みの場合は新規Window作る
  else if listProcess = {} then
    tell application "Terminal"
      set objNewWindow to (do script "\n")
    end tell
  end if
end if
delay 0.5
##############################
## コマンド実行
tell application "Terminal"
do script strCommandText in objNewWindow
end tell
delay 1
log "コマンド実行中"

##############################
## コマンド終了チェック
(*
objNewWindowにWindowIDとTabIDが入っているので
objNewWindowに対してbusyを確認する事で
処理が終わっているか?がわかる
*)
## 無限ループ防止で100回
repeat 100 times
  tell application "Terminal"
    set boolTabStatus to busy of objNewWindow
  end tell
  if boolTabStatus is false then
    log "コマンド処理終了しました"
    tell application "Terminal"
      tell front window
tell front tab
set listProcess to processes as list
end tell
      end tell
    end tell
    set numCntProcess to (count of listProcess) as integer
    if numCntProcess ≤ 2 then
      exit repeat
    else
      delay 1
    end if
    --->このリピートを抜けて次の処理へ
  else if boolTabStatus is true then
    log "コマンド処理中"
    delay 1
    --->busyなのであと1秒まつ
  end if
end repeat
##############################
## control Cを送る
tell application "System Events"
  tell process "Terminal"
    keystroke "c" using {control down}
  end tell
end tell
##############################
## control Cを送る
tell application "System Events"
  tell process "Terminal"
    keystroke "c" using {control down}
  end tell
end tell

##############################
## exit打って終了
tell application "Terminal"
do script "exit" in objNewWindow
end tell
##############################
## exitの処理待ちしてClose
repeat 20 times
  tell application "Terminal"
    tell front window
      tell front tab
set listProcess to processes as list
      end tell
    end tell
  end tell
  if listProcess = {} then
    tell application "Terminal"
      tell front window
# tell front tab
close saving no
# end tell
      end tell
    end tell
    exit repeat
  else
    delay 1
  end if
end repeat


|

[Terminal]コマンド実行後に閉じる


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use scripting additions

property refMe : a reference to current application

##############################
#####ダイアログを前面に
##############################
tell current application
  set strName to name as text
end tell
###スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
##############################
#####クリップボードの内容取得
##############################
set ocidPasteboard to refMe's NSPasteboard's generalPasteboard()
set ocidPastBoardTypeArray to ocidPasteboard's types
set boolContain to ocidPastBoardTypeArray's containsObject:"public.utf8-plain-text"
if boolContain = true then
  set strReadString to (the clipboard as text)
else
  set boolContain to ocidPastBoardTypeArray's containsObject:"NSStringPboardType"
  if boolContain = true then
    set ocidReadString to ocidPasteboard's readObjectsForClasses:({refMe's NSString}) options:(missing value)
    set strReadString to ocidReadString as text
  else
    log "テキストなし"
    set strReadString to "COMMANDを入力" as text
  end if
end if
set aliasIconPath to (POSIX file "/System/Applications/Utilities/Terminal.app/Contents/Resources/Terminal.icns") as alias
try
  set objResponse to (display dialog "入力したコマンドをターミナルで実行します" with title "入力してください" default answer strReadString buttons {"OK", "キャンセル"} default button "OK" cancel button "キャンセル" with icon aliasIconPath giving up after 120 without hidden answer)
on error
  log "エラーしました"
return "エラーしました"
  error number -128
end try
if true is equal to (gave up of objResponse) then
return "時間切れですやりなおしてください"
  error number -128
end if
if "OK" is equal to (button returned of objResponse) then
  set theResponse to (text returned of objResponse) as text
else
  log "エラーしました"
return "エラーしました"
  error number -128
end if
##############################
## 実行するコマンド
set strCommandText to theResponse as text
##############################
tell application "Terminal" to activate
delay 0.2
## 実行中チェック
tell application "Terminal"
  set numCntWindow to (count of every window) as integer
end tell
delay 0.5
if numCntWindow = 0 then
  log "Windowないので新規で作る"
  tell application "Terminal"
    set objNewWindow to (do script "\n")
  end tell
else
  log "Windowがある場合は、何か実行中か?をチェック"
  tell application "Terminal"
    tell front window
      tell front tab
set boolTabStatus to busy as boolean
set listProcess to processes as list
      end tell
    end tell
    set objNewWindow to selected tab of front window
  end tell
  ###前面のタブがbusy=実行中なら新規Window作る
  if boolTabStatus = true then
    tell application "Terminal"
      set objNewWindow to (do script "\n")
    end tell
    ###前面のタブにプロセスが無い場合=exit済みの場合は新規Window作る
  else if listProcess = {} then
    tell application "Terminal"
      set objNewWindow to (do script "\n")
    end tell
  end if
end if
delay 0.5
##############################
## コマンド実行
tell application "Terminal"
do script strCommandText in objNewWindow
end tell
delay 1
log "コマンド実行中"

##############################
## コマンド終了チェック
(*
objNewWindowにWindowIDとTabIDが入っているので
objNewWindowに対してbusyを確認する事で
処理が終わっているか?がわかる
*)
## 無限ループ防止で100回
repeat 100 times
  tell application "Terminal"
    set boolTabStatus to busy of objNewWindow
  end tell
  if boolTabStatus is false then
    log "コマンド処理終了しました"
    tell application "Terminal"
      tell front window
tell front tab
set listProcess to processes as list
end tell
      end tell
    end tell
    set numCntProcess to (count of listProcess) as integer
    if numCntProcess ≤ 2 then
      exit repeat
    else
      delay 1
    end if
    --->このリピートを抜けて次の処理へ
  else if boolTabStatus is true then
    log "コマンド処理中"
    delay 1
    --->busyなのであと1秒まつ
  end if
end repeat



##############################
## exit打って終了
tell application "Terminal"
do script "exit" in objNewWindow
end tell
##############################
## exitの処理待ちしてClose
repeat 20 times
  tell application "Terminal"
    tell front window
      tell front tab
set listProcess to processes as list
      end tell
    end tell
  end tell
  if listProcess = {} then
    tell application "Terminal"
      tell front window
# tell front tab
close saving no
# end tell
      end tell
    end tell
    exit repeat
  else
    delay 1
  end if
end repeat


|

その他のカテゴリー

Acrobat Acrobat Annotation Acrobat Dialog Acrobat Form Acrobat JS Acrobat Open Acrobat Plugin Acrobat python Acrobat Reader Acrobat Sequ Acrobat Stamps Admin Admin Account Admin Apachectl Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Permission Admin Pkg Admin Power Management Admin Printer Admin SetUp Admin SMB Admin System Information Admin Tools Admin Users Admin Volumes Adobe Apple AppleScript AppleScript Guide AppleScript Accessibility AppleScript AppKit AppleScript Applications AppleScript AppStore AppleScript Archive AppleScript Attributes AppleScript Automator AppleScript AVAsset AppleScript AVconvert AppleScript AVFoundation AppleScript AVURLAsset AppleScript BackUp AppleScript Barcode AppleScript Bash AppleScript Basic AppleScript Basic Path AppleScript Bluetooth AppleScript BOX AppleScript Browser AppleScript Calendar AppleScript CD/DVD AppleScript Choose AppleScript Chrome AppleScript CIImage AppleScript CloudStorage AppleScript Color AppleScript com.apple.LaunchServices.OpenWith AppleScript Console AppleScript Contacts AppleScript CotEditor AppleScript CURL AppleScript current application AppleScript Date&Time AppleScript delimiters AppleScript Desktop AppleScript Device AppleScript Disk AppleScript do shell script AppleScript Dock AppleScript DropBox AppleScript eMail AppleScript Encode Decode AppleScript Error AppleScript EXIFData AppleScript ffmpeg AppleScript File AppleScript Finder AppleScript Firefox AppleScript Folder AppleScript Fonts AppleScript GIF AppleScript HTML AppleScript Icon AppleScript Illustrator AppleScript Image Events AppleScript Image2PDF AppleScript ImageOptim Applescript iWork AppleScript Javascript AppleScript Jedit AppleScript Json AppleScript Label AppleScript List AppleScript locationd AppleScript LRC AppleScript LSSharedFileList AppleScript m3u8 AppleScript MakePDF AppleScript Map AppleScript Math AppleScript Microsoft AppleScript Microsoft Edge AppleScript Microsoft Excel AppleScript Mobileconfig AppleScript Mouse AppleScript Movie AppleScript Music AppleScript NetWork AppleScript Notes AppleScript NSArray AppleScript NSBitmapImageRep AppleScript NSBundle AppleScript NSCFBoolean AppleScript NSCharacterSet AppleScript NSColor AppleScript NSColorList AppleScript NSData AppleScript NSDictionary AppleScript NSError AppleScript NSEvent AppleScript NSFileAttributes AppleScript NSFileManager AppleScript NSFont AppleScript NSFontManager AppleScript NSImage AppleScript NSIndex AppleScript NSKeyedArchiver AppleScript NSKeyedUnarchiver AppleScript NSLocale AppleScript NSMutableArray AppleScript NSMutableDictionary AppleScript NSMutableString AppleScript NSNotFound AppleScript NSNumber AppleScript NSOpenPanel AppleScript NSPasteboard AppleScript NSPDFImageRep AppleScript NSpoint AppleScript NSPredicate AppleScript NSRange AppleScript NSRegularExpression AppleScript NSRunningApplication AppleScript NSScreen AppleScript NSSize AppleScript NSString AppleScript NSStringCompareOptions AppleScript NSTask AppleScript NSTimeZone AppleScript NSURL AppleScript NSURL File AppleScript NSURLBookmark AppleScript NSURLComponents AppleScript NSURLResourceKey AppleScript NSUserDefaults AppleScript NSUUID AppleScript NSView AppleScript NSWorkspace AppleScript Numbers AppleScript OAuth AppleScript ObjC AppleScript OneDrive AppleScript Osax AppleScript PDF AppleScript PDFAnnotationWidget AppleScript PDFContext AppleScript PDFDisplayBox AppleScript PDFDocumentPermissions AppleScript PDFKit AppleScript PDFnUP AppleScript PDFOutline AppleScript Photos AppleScript Photoshop AppleScript Plist System Events AppleScript PostScript AppleScript prefPane AppleScript Preview AppleScript Python AppleScript QR AppleScript QR Decode AppleScript QuickLook AppleScript QuickTime AppleScript record AppleScript Regular Expression AppleScript Reminders AppleScript ReName AppleScript Repeat AppleScript RTF AppleScript Safari AppleScript SaveFile AppleScript ScreenCapture AppleScript ScreenSaver AppleScript Script Editor AppleScript Script Menu AppleScript Shortcuts AppleScript Shortcuts Events AppleScript Sort AppleScript Sound AppleScript Spotlight AppleScript SRT AppleScript StandardAdditions AppleScript stringByApplyingTransform AppleScript System Events AppleScript System Settings AppleScript TemporaryItems AppleScript Terminal AppleScript Text AppleScript Text CSV AppleScript Text TSV AppleScript TextEdit AppleScript Translate AppleScript Trash AppleScript Twitter AppleScript UI AppleScript Unit Conversion AppleScript UTType AppleScript valueForKeyPath AppleScript Video AppleScript VisionKit AppleScript Visual Studio Code AppleScript webarchive AppleScript webp AppleScript Wifi AppleScript XML AppleScript XML EPUB AppleScript XML OPML AppleScript XML Plist AppleScript XML RSS AppleScript XML SVG AppleScript XML TTML AppleScript XML webloc AppleScript YouTube AppleScript Zero Suppress Applications Barcode OnLine Tools CityCode Design iPhone List Logs lsappinfo Memo Music perl PlistBuddy pluginkit postalcode ReadMe SF Symbols character id SF Symbols Entity sips Skype Slack sqlite TCC Tools Typography Video Wacom zoom