How to pass a variable as an argument in Bash

246 views Asked by At

I'm trying to change my Mac OS X desktop background using osascript script. Everything works fine if I use everything as static. But if I try to introduce a variable everything goes haywire.

My code is below.

#! /bin/bash

function random_wall () 
{
    path_name="/Users/Furkan/Pictures/Selection/"
    my_number=$[RANDOM%$1+1]
    my_wall="$path_name$2-$my_number.jpg"
    sec1='tell application "System Events" to set picture of every desktop to ("'
    sec1+=$my_wall
    sec2='" as POSIX file as alias)'
    sec1+=$sec2
    echo $sec1
    # This one does not work
    osascript -e $sec1
    # The one below works
    osascript -e 'tell application "System Events" to set picture of every desktop to ("/Users/Furkan/Pictures/Selection/night-3.jpg" as POSIX file as alias)'
}

hour=$(date +"%H")
if [ $hour -ge "5" ] && [ $hour -le "9" ]
then
random_wall 8 early-morning
fi

if [ $hour -ge "9" ] && [ $hour -lt "13" ] 
then
random_wall 17 morning
fi

if [ $hour -ge "13" ] && [ $hour -lt "17" ]
then
random_wall 19 midday
fi

if [ $hour -ge "17" ] && [ $hour -lt "20" ]
then
random_wall 15 afternoon
fi

if [ $hour -ge "20" ] || [ $hour -lt "5" ]
then
random_wall 19 night
fi

I have checked the output. The code below to test it, the static file version is working as intended. However, when I try to pass my variable as an argument I'm getting the following error.

4:4: syntax error: Expected expression but found end of script. (-2741)

To sum up, I'm confused how to handle the arguments given the single and double quotes' involvement.

1

There are 1 answers

0
Furkanicus On BEST ANSWER

I've just come across a solution which I never thought it would have been this easy. All that I needed to do was to wrap my variable name with double quotes.

osascript -e "$sec1"