Passing a script parameter into osascript in shell to create file path

mags
New Contributor II

I'd like to pass a file name via a default script parameter into a bash script which calls an osascript, but am running into problems.

I've been fiddling around with something like the below, but am continually getting errors. The script does work perfectly if I hard-code the full path, and the file exists, so it must be something to do with pulling in the parameter.

$4 is set to green.png in my policy

Any ideas out there?

#!/bin/sh

if [ "$4" != "" ]
then
    osascript -e 'tell application "System Events" to set picture of every desktop to ("/Library/Desktop\\ Pictures/$4" as POSIX file as alias)'
fi 

exit 0
1 ACCEPTED SOLUTION

mm2270
Legendary Contributor III

Try this:

#!/bin/sh

if [ "$4" != "" ]; then
    /usr/bin/osascript << EOD
set imageName to do shell script "echo "$4""
tell application "System Events" to set picture of every desktop to ("/Library/Desktop Pictures/" & imageName as POSIX file as alias)
EOD
fi

exit 0

Edit: Changed script back to using $4

View solution in original post

4 REPLIES 4

mm2270
Legendary Contributor III

Try this:

#!/bin/sh

if [ "$4" != "" ]; then
    /usr/bin/osascript << EOD
set imageName to do shell script "echo "$4""
tell application "System Events" to set picture of every desktop to ("/Library/Desktop Pictures/" & imageName as POSIX file as alias)
EOD
fi

exit 0

Edit: Changed script back to using $4

Serge
New Contributor III

The variable needs to be escaped with double quotes, single quotes and double quotes again to properly escape the osascript command and pass the variable.

osascript -e 'tell application "System Events" to set picture of every desktop to ("/Library/Desktop\\ Pictures/"'"$4"'" as POSIX file as alias)'

mags
New Contributor II

Thanks both so much for answering - @mm2270 That is spot on - thank you so much - that has been driving me and my colleagues crazy for about 2 days!!

mmcchesney
New Contributor II

man thanks I had a similar issue that ""$VARIABLE"" was hanging us up too. Thanks for the assist.