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

在Bash脚本中执行youtube-dl命令时遭遇`syntax error near unexpected token '('`错误

Fixing Syntax Error When Running youtube-dl in Bash Script

Hey there, let's break down why you're hitting that syntax error near unexpected token '(' and how to fix it properly.

What's Causing the Error?

The core issue here is how eval parses your command string, combined with your current approach to storing the command:

  • When you save the command in a string and run it with eval, Bash tries to interpret %(ext)s as shell syntax. Parentheses have special meaning in Bash (like for subshells or command substitution), so it throws an error instead of passing that placeholder directly to youtube-dl.
  • On top of that, if $title or $filename contain spaces, quotes, or other special characters, this string-based approach will break even more—your command will split parameters incorrectly.

The Proper Fix: Use a Command Array

Instead of storing the command as a single string, use a Bash array to hold each argument separately. This is the standard, robust way to handle commands with special characters or dynamic parameters:

# Build the command as an array
youtube_dl_cmd=(
    youtube-dl
    --prefer-ffmpeg
    -o "$title.%(ext)s"
    "$filename"
)

# Execute the command
"${youtube_dl_cmd[@]}"

Why This Works

  • Arrays keep each argument as a distinct element. Bash won't try to parse the %(ext)s placeholder as shell syntax—it'll pass it exactly as-is to youtube-dl.
  • When you expand the array with "${youtube_dl_cmd[@]}", each element is treated as a single command-line argument. Even if $title or $filename have spaces or special characters, they'll be handled correctly without unintended splitting.

If you absolutely have to use a string and eval (we don't suggest this—it's error-prone and hard to maintain), you'd need to escape the parentheses so Bash doesn't interpret them:

youtube="youtube-dl -prefer-ffmpeg -o $title.\%(ext\)s ${filename}"
eval "$youtube"

But again, the array method is far more reliable for any real-world script.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:06:37