Tuesday, April 13, 2021

#1 2021-04-05 06:22:06 am

Fredrik71
Member
Registered: 2019-10-23
Posts: 666

Target of Finder window 1 with Shell command

The command in application Finder target of Finder window 1 could be very useful
in shell scripting or navigation in Terminal.

What if we could only type 3 character long string in Terminal and get target of Finder window 1
Some clever person did and I like to share it with you here.

The script below should be attached to ~/.bash_profile (bash)

Now you could navigate in Finder to any directory and in Terminal you type cdf (return)

# prints the path of the front Finder window. Desktop if no window open
function pwdf () {
    osascript <<EOS
        tell application "Finder"
            if (count of Finder windows) is 0 then
                set dir to (desktop as alias) -- defaults if no Finder window is open.
            else
                set dir to ((target of Finder window 1) as alias)
            end if
            return POSIX path of dir
        end tell
EOS
}

# changes directory to frontmost
alias cdf='pwdf; cd "$(pwdf)"'


if you are the expert, who will you call if its not your imagination.

Offline

 

#2 2021-04-06 01:26:02 am

alastor933
Member
From:: Utrecht, NL
Registered: 2008-09-12
Posts: 581

Re: Target of Finder window 1 with Shell command

I can see that would be quite useful. But…

Fredrik71 wrote:

The script below should be attached to ~/.bash_profile (bash)

…please explain to this Terminal novice how to do that.

Offline

 

#3 2021-04-06 08:37:10 am

Fredrik71
Member
Registered: 2019-10-23
Posts: 666

Re: Target of Finder window 1 with Shell command

In bash scripting you could make function

ex.

function hello () {
   echo Hello World!
}

But you could also put function in configure file for bash.
The way I do it: open terminal and make sure you are in your home directory that is default.
type in Terminal nano .bash_profile copy my script and paste it.
restart Terminal and type in Terminal cdf.

You could see in the script the function name is pwdf. To make it work we use alias (bash) that you
could see in the last row in the script.

pwdf  only give you POSIX path of (target of Finder window 1) as string
and the alias cdf do the magic to add cd before pwdf.

Last edited by Fredrik71 (2021-04-07 02:44:15 am)


if you are the expert, who will you call if its not your imagination.

Offline

 

Board footer

Powered by FluxBB

RSS (new topics) RSS (active topics)