Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use `pbcopy` as path for cd command

I am using Automator on my Mac to set up a service that passes a selected folder to a bash shell script as arguments. In the script I do:

for f in "$@"; do
    printf "%q\n" "$f" | pbcopy
done

if I then do:

echo `pbpaste`

I get the path to my selected folder with spaces escaped (\). I then wanted to use this path to cd into that directory and do a bunch of other stuff (creating a blank directory structure). I hoped I could just do:

cd `pbpaste`

but this doesn't work. If I type the path manually the cd works so I assume the is some issue with data types or returns or something??

I'll admit I don't really know what this script actually doing and may be going about this all wrong but but if anyone can explain what's going on here and how to get it working it that would be great but even better would be a pointer to a really good resource for a complete beginner to start learning about shell scripting. I really like the idea of getting into this a bit more but all the resources I have found are either total basics (cd, ls, pwd etc) or really high level and assume a bunch of previous knowledge. What I'd really like is a full language reference with some actual examples like you find for the languages I am more used to (HTML/CSS/JS/AS3), if such a thing exists.

Cheers for any help :)

like image 316
popClingwrap Avatar asked Oct 21 '25 15:10

popClingwrap


2 Answers

I'm agree with @chepner's answer, but for google's results sake, to cd using pbpaste you simply do:

cd $(pbpaste)
like image 62
Yëco Avatar answered Oct 23 '25 14:10

Yëco


When you use the %q format, you are adding literal backslashes to the string, which the shell does not process as escape characters when you use it with cd.

The clipboard is useful for interprocess communication; inside a single script, it's easier to just use variables to hold information temporarily. f already has the path name in it, so just use it:

cd "$f"

Notice I've quoted the expansion of f, so that any spaces in the path name are passed as part of the single argument to cd.

like image 26
chepner Avatar answered Oct 23 '25 15:10

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!