How to cd to passed in path in Applescript?

This is not directly related to Keyboard Maestro as I am trying to create an applescript that I will save as .app to run but I can’t figure out how to do it.

I have an applescript that looks like this :

on run {input, parameters}
	tell application "iTerm"
		if exists window 1 then
			tell current window
				tell current session to write text "cd " & input
			end tell
		else
			create window with default profile
			tell current window
				tell current session to write text "cd " & input
			end tell
		end if
	end tell
	
	tell application "System Events"
		if frontmost of process "iTerm2" is false then key code 13 using {option down, control down, shift down, command down}
	end tell
end run 

I then have an automator workflow setup like so :

Although in the end the path will be passed in to the .app so Get Specified Finder Items will go away.

The reason this doesn’t work I think is due to the fact that input is an HFS path and I have to convert it to a string perhaps to add to the shell command there. I searched everywhere how to do that and I have no idea how though. :frowning:

Thank you for any help.

Instead of trying to use the iTerm app, you would be better of using do shell script in AppleScript.

Search the Internet for “AppleScript shell script” for lots of help/examples.

Yeah but I want to cd to a folder in my current iTerm tab.

Why not use a simple KM Insert Text by Pasting Action?

I am trying to solve this issue. So I have to save i as .app

Would love to use Keyboard Maestro instead but I don’t think I can.

Shell scripts run on Unix, and always use a POSIX path.

If the AppleScript variable "input" is a HFS path, then you can convert it to POSIX path like this:

set inputPath to POSIX path of input

Also, just to be sure, I'd write your script like this:

on run {input, parameters}

  set cmdStr to "cd " & (POSIX path of input)
  
  tell application "iTerm"
    if exists window 1 then
      tell current window
        tell current session to write text cmdStr
              end tell
    else
      create window with default profile
      tell current window
        tell current session to write text cmdStr
      end tell
    end if
  end tell

I don't have the iTerm app, so I can't test, or even compile this script.
So you will have to double check it.

1 Like

That works wonderfully well. Thank you so much @JMichaelTX :green_heart:

1 Like