【问题标题】:Syntax error: "(" unexpected in bash script语法错误:“(”在 bash 脚本中出现意外
【发布时间】:2014-08-25 23:04:16
【问题描述】:

编辑:我已经修复了我的脚本。它似乎正在工作。如果有人有任何改进建议,我会很乐意提供帮助。显然我需要使用 bash 而不是 sh 来运行它。 这是更新后的脚本:

#!/bin/bash
for file in /home/corey/box/*/*
do
dir=$(basename $"(dirname "$file")")
sudo chmod 0777 /var/log/torrentwatch.log
sudo chmod -R 0777 /home/corey/box/*/*
if [[ "$file" = /home/corey/box/*/*.torrent ]]
then
echo "[$(date)]" "$file added to queue." >> /var/log/torrentwatch.log
/usr/bin/transmission-remote localhost:9091 --auth=transmission:transmission -w /media/Media/Torrents/"$dir" -a "$file"
sleep 40 && rm "$file"
sleep 3 && sudo chmod -R 777 /media/Media && sudo chown -R debian-transmission:debian-transmission /media/Media/info
fi
done

该脚本用于将 torrent 文件添加到文件夹并将它们添加到传输中。这是脚本的原始版本:

#!/bin/bash
for file in /home/me/box/*/*
do
dir=$(basename $(dirname "$file"));
sudo chmod 0777 /var/log/torrentwatch.log
sudo chmod -R 0777 /home/me/box/*/*
if "$file" = "/home/me/box/*/*.torrent"; then
echo [`date`] "$file" added to queue. >> /var/log/torrentwatch.log
/usr/bin/transmission-remote localhost:9091 --auth=transmission:transmission -l -w /media/Media/Torrents/$dir -a "$file"
sleep 40 && rm "$file"
sleep 3 && sudo chmod -R 777 /media/Media && sudo chown -R debian-transmission:debian-transmission /media/Media/info
fi
done

问题是当我运行脚本时,我得到了

/home/me/box/TV/Name.of.file.torrent: Syntax error: "(" unexpected

我尝试使用 bash、sh 和 zsh 运行脚本,但似乎都没有。我无法弄清楚问题是什么。

【问题讨论】:

  • 你的 if 语句是错误的——if [[ $file = /home/me/box/*/*.torrent ]] 会起作用。您的回声需要更多报价——echo "[$(date)] $file added to queue" 会更安全。你需要引用你的扩展——任何你使用$dir的地方都需要在双引号内。
  • 缩进你的代码会让它更更容易阅读。
  • 不是对 Keith 的回应,而是 dir=$(basename $(dirname "$file")) 在文件已被 dirname 剥离后尝试获取文件的 文件名 (basename)。
  • 跟进我之前的评论,显然/home/me/box/TV/Name.of.file.torrent 具有执行权限(尽管没有充分的理由),并且脚本正在尝试执行它。如果没有#! 行,它将由/bin/sh 执行,从而产生该错误消息。修复if 条件将避免执行*.torrent 文件。 (并且在不需要可执行的任何文件(不是目录!)上执行chmod -x 是个好主意。)
  • @user450632,那么您正在使用sh 运行您的脚本,而不是bash。由于您的 shebang 是正确的 (#!/bin/bash),我认为您明确地以 sh yourscript.sh 开头;不要那样做。 (也可能是您的 shebang 之前有 cmets 或其他字符;它需要位于文件的最顶部)。 sh 不支持内置模式匹配,这是您当前制定的代码所需要的。

标签: bash syntax-error sh


【解决方案1】:

这是最直接的问题:

if "$file" = "/home/me/box/*/*.torrent"

它正在运行以下内容:

/home/me/box/TV/Name.of.file.torrent = "/home/me/box/*/*.torrent"

...也就是说,它试图将.torrent 文件作为脚本启动(其第一个参数为=,第二个参数为/home/me/box/*/*.torrent),这会产生语法错误。相反,使用:

if [[ $file = /home/me/box/*/*.torrent ]]

此脚本的其他地方还有其他问题——我强烈建议通过http://shellcheck.net/ 运行它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 2015-06-08
    • 2015-11-09
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    • 1970-01-01
    相关资源
    最近更新 更多