如何在 Bash 中将变量作为参数传递

How to pass a variable as an argument in Bash

我正在尝试使用 osascript 脚本更改我的 Mac OS X 桌面背景。如果我将所有内容都用作静态,则一切正常。但是,如果我尝试引入一个变量,一切都会变得一团糟。

我的代码如下。

#! /bin/bash

function random_wall () 
{
    path_name="/Users/Furkan/Pictures/Selection/"
    my_number=$[RANDOM%+1]
    my_wall="$path_name-$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

我已经检查了输出。下面的代码对其进行测试,静态文件版本按预期工作。但是,当我尝试将我的变量作为参数传递时,出现以下错误。

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

总而言之,考虑到单引号和双引号的参与,我很困惑如何处理参数。

我刚刚遇到一个解决方案,我从没想过它会这么简单。我需要做的就是用双引号将我的变量名括起来。

osascript -e "$sec1"