Shell 脚本在 ksh 中给出错误

Shell script giving errors in ksh

我有一个脚本在 Bash shell(使用 Red Hat Linux)中执行时运行良好,但是这个相同的脚本在 Solaris 10 (DB) 服务器上失败其中 ksh 用于执行此脚本。该脚本基本上从文件中逐行读取并执行存储过程(在 Oracle 中)。下面是我的脚本:

#/bin/sh

for i in $(cat subscriber.txt); do

        SUBSCRIBER_ID="'$i'"
        sqlplus -s myuser/myuser  <<EOF
        execute delete_learnings($SUBSCRIBER_ID);
        commit;
        EXIT    
EOF
done

我得到的错误是:

./removeLearnings.sh: syntax error at line 3: `$' unexpected

知道可能出了什么问题吗?我应该更改脚本以具有 ksh 吗?我无法在这台机器上调试,因为它是一个客户环境(我无权访问)。

问题是 $(...) 结构,它 POSIX 兼容但不受遗留 Bourne shell 支持,/bin/sh 在 Solaris 10 及更早版本上。

您可以替换您的 shebang 来调用 Solaris POSIX 兼容 shell:

#!/usr/xpg4/bin/sh

或使用此旧语法(不太推荐):

for i in `cat subscriber.txt`; do

您正在尝试在 ksh (Korn shell) 上执行 sh( bourne shell) 脚本。尝试将 shebang (#!/bin/bash) 更改为 (#!/bin/ksh)

无论如何,用for循环文本文件是个坏主意。请参阅 http://mywiki.wooledge.org/BashFAQ/001- 推荐的语法也更便携:

while read stuff; do
    : things with "$stuff"
done <subscriber.txt

您通常会使用 read -r,但我不知道在 Solaris 上是否可用。

然而,shell 循环通常是完全错误的方法。单个 SQL 调用要好得多,也更健壮:

( sed 's/.*/execute delete_learnings(&);/'
  printf "commit;\nEXIT\n" ) |
sqlplus -s myuser/myuser