You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash调用AppleScript发消息报错:部分消息无法发送(错误-2741)

问题解决与脚本优化

一、现有脚本错误的根源与修复

你遇到的130:132: syntax error: Expected end of line, etc. but found real number. (-2741)错误,核心原因是Here Document的结束标记END格式不符合要求。

查看你的代码可以发现,第2、3个END行后带有多余的空格或制表符,导致Bash没有正确识别结束标记,把后续的sleep .1也当成了AppleScript代码的一部分。AppleScript解析到.1这个实数时,直接触发了语法错误。

修复后的基础脚本

#!/bin/bash

printf 'Starting Text Script... \nWhat number would you like to text?\n'
read number

msg="When..."
/usr/bin/osascript - "$@" << END
tell application "Messages" to send "$msg" to buddy "$number" 
END
sleep .1

msg="Cause..."
/usr/bin/osascript - "$@" << END
tell application "Messages" to send "$msg" to buddy "$number" 
END
sleep .1

msg="Laughing..."
/usr/bin/osascript - "$@" << END
tell application "Messages" to send "$msg" to buddy "$number" 
END
sleep .1

msg="Like..."
/usr/bin/osascript - "$@" << END
tell application "Messages" to send "$msg" to buddy "$number" 
END
sleep .1

注意:每个END必须单独占一行,前后不能有任何空格、制表符或其他字符。

如果后续需要发送包含特殊字符(单引号、双引号等)的消息,建议改用参数传递的方式避免转义问题:

#!/bin/bash

printf 'Starting Text Script... \nWhat number would you like to text?\n'
read number

send_msg() {
    local msg="$1"
    /usr/bin/osascript - "$number" "$msg" <<'END'
        on run {target_number, target_msg}
            tell application "Messages"
                send target_msg to buddy target_number
            end tell
        end run
END
}

send_msg "When..."
sleep .1
send_msg "Cause..."
sleep .1
send_msg "Laughing..."
sleep .1
send_msg "Like..."
sleep .1

这里用<<'END'禁止Bash展开Here Document内的变量,通过AppleScript的on run参数接收内容,能规避绝大多数字符转义问题。

二、优化脚本:支持号码输入与文件批量发送

修改脚本后,可通过命令行参数传入目标号码和消息文件路径,文件中每行内容将作为单独消息发送:

#!/bin/bash

# 检查参数数量
if [ $# -ne 2 ]; then
    printf "Usage: %s <target-number> <message-file-path>\n" "$0"
    exit 1
fi

target_number="$1"
message_file="$2"

# 检查文件是否存在
if [ ! -f "$message_file" ]; then
    echo "Error: File '$message_file' does not exist."
    exit 1
fi

# 定义发送消息函数
send_msg() {
    local number="$1"
    local msg="$2"
    /usr/bin/osascript - "$number" "$msg" <<'END'
        on run {target_num, target_msg}
            tell application "Messages"
                send target_msg to buddy target_num
            end tell
        end run
END
}

# 逐行读取文件发送消息
while IFS= read -r line; do
    # 跳过空行
    [ -z "$line" ] && continue
    send_msg "$target_number" "$line"
    sleep 0.1
done < "$message_file"

echo "All messages sent successfully."

使用方法

  1. 将脚本保存为send_messages.sh
  2. 赋予执行权限:chmod +x send_messages.sh
  3. 运行脚本:./send_messages.sh "1234567890" ./joke_messages.txt
    • 其中1234567890是目标号码,./joke_messages.txt是存储消息的文件(每行一条消息)

这个版本的优势:

  • 彻底避免字符转义问题,支持特殊内容的消息
  • 批量处理文件消息,灵活度更高
  • 带有参数校验和错误提示,稳定性更强

内容的提问来源于stack exchange,提问作者Red Fang110

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 08:31:02