首页 > 解决方案 > 在mac的命令bash文件中使用变量

问题描述

我创建了一个 bash 脚本,用于在 mac OS 中显示通知 5 秒。

#!/bin/bash

arr[0]="0"
arr[1]="1"
arr[2]="2"
arr[3]="3"
arr[4]="4"
arr[5]="5"
arr[6]="6"

while true; do
 
    rand=$[$RANDOM % ${#arr[@]}]
    text=${arr[$rand]}
    
    osascript -e 'display notification '"$text"' with title "hello"'

    sleep 5
done

但显示带有标题 hello 和描述 $text 的通知。如何在此命令中使用 $text 变量?

标签: bashmacosshzshoh-my-zsh

解决方案


将 的值"$text"作为参数传递给静态脚本。

osascript -e 'on run argv' \
          -e 'display notification (item 1 of argv) with title "hello"' \
          -e 'end run' "$text"

或者

osascript -e 'on run argv
display notification (item 1 of argv) with title "hello"
end run' "$text"

顺便说一句,$[...]它是一种非常古老且非常过时的算术扩展形式。改为使用$((...))


推荐阅读