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

终端使用terminal-notifier发送多字符串消息的Shell脚本问题

解决Shell脚本中terminal-notifier无法识别带空格消息的问题

这是典型的Shell变量展开时的**单词拆分(Word Splitting)**问题,我来给你拆解清楚原因和解决办法:

问题根源

当你在脚本里直接写-message $msg时,Shell会把变量msg里的空格当作参数分隔符,把"multi string with space"拆成multi、string、with、space四个独立的参数传给terminal-notifier。而-message只需要一个参数,所以程序只会读取第一个词multi,剩下的内容会被当成无效参数处理,自然就无法显示完整消息了。

解决方案

下面几种方法都能完美解决这个问题,按场景选择即可:

1. 用双引号包裹变量(最常用)

把变量用双引号括起来,Shell就会把整个字符串当作一个完整参数传递,不会拆分空格:

msg="multi string with space"
terminal-notifier -title 'testing' -message "$msg"

2. 用printf格式化(处理特殊字符更安全)

如果你的消息里可能包含引号、反斜杠这类特殊字符,用printf来格式化输出会更稳妥:

msg="multi string with space and \"quotes\""
terminal-notifier -title 'testing' -message "$(printf '%s' "$msg")"

3. 用数组构建命令(适合多参数场景)

如果你的通知命令有很多参数,用数组来存储命令和参数,展开时能确保每个参数的完整性:

msg="multi string with space"
notify_command=(terminal-notifier -title 'testing' -message "$msg")
"${notify_command[@]}"

"${notify_command[@]}"会把数组里的每个元素作为独立参数传递,完全保留空格和特殊字符。

验证示例

写个简单脚本测试一下:

#!/bin/bash
msg="Hello World! This is a multi-line message too"

# 错误写法:只会显示"Hello"
terminal-notifier -title 'Wrong' -message $msg

# 正确写法:显示完整消息
terminal-notifier -title 'Correct' -message "$msg"

内容的提问来源于stack exchange,提问作者Sharath BJ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:54:46