3

我通常会SQL在 Bash shell 脚本中内联编写语句,以便在SQLPlusas-中执行

#! /bin/sh

sqlplus user/pwd@dbname<<EOF
insert into dummy1 
select * from dummy2;

commit;
exit;
EOF

dummy1这可以正常工作,并且在执行时会插入行。前几天我的一位同事带着如下脚本来找我(简化)

#! /bin/sh    
sqlvar="insert into dummy1 select * from dummy2;commit;"    
echo $sqlvar|sqlplus user/pwd@dbname

这样做的问题是,当执行该变量时,该变量sqlvar将扩展*为当前目录中的所有文件,并最终会出错,例如-

SQL> insert into dummy1 select <--all the file names in the current directory--> 
from dummy2;commit
                                                    *
ERROR at line 1:
ORA-00923: FROM keyword not found where expected

我们对此的第一个立场是 shell*在通配符上下文中解释并在 shell 变量扩展时列出所有文件名(不太清楚为什么......???)。所以,为了理解这一点,我们做了如下的事情——

$ var="hello *"
$ echo $var
hello <--all the file names in the current directory-->

$*
ksh: somefile.sh: 0403-006 Execute permission denied. #since it had no execute permission

目录中还有许多其他文件,我不确定为什么*选择执行somefile.sh或指向somefile.sh.

经过一番挖掘,我们意识到,使用set -o noglob可以完全解决这个问题,比如——

#! /bin/sh
set -o noglob
sqlvar="insert into dummy1 select * from dummy2;\n commit;"    
echo $sqlvar|sqlplus user/pwd@dbname

互联网上有一些关于setting的相互矛盾或相当矛盾的描述。noglob所以我正在寻找是否有人可以解释这一点的诀窍。

4

2 回答 2

13

经过一番挖掘,我们意识到,使用 set -o noglob 可以完全解决这个问题

它并没有解决问题,而是隐藏了它。手头的问题是缺乏引用。引用变量通常是一个好习惯,因为当变量包含特殊字符、空格等时,它可以防止 shell 做意外的事情。

禁用通配确实会阻止*扩展,但这通常不是您想要做的事情。它会让你使用*and ?,但如果你使用其他特殊字符,事情可能会中断。

目录中还有许多其他文件,我不确定为什么 * 选择执行 somefile.sh 或指向 somefile.sh。

这里*展开为当前目录下的所有文件名,然后这个文件列表就变成了命令行。shell 最终会尝试按字母顺序执行第一个文件名。


因此,解决此问题的正确方法是引用变量:

echo "$sqlvar" | sqlplus user/pwd@dbname

这将解决通配符问题。另一个问题是您需要将\n转义序列解释为换行符。Shell 不会自动执行此操作。要\n上班,请使用echo -e

echo -e "$sqlvar" | sqlplus user/pwd@dbname

或者使用字符串文字语法$'...'。那是前面带有美元符号的单引号。

sqlvar=$'insert into dummy1 select * from dummy2;\n commit;'
echo "$sqlvar" | sqlplus user/pwd@dbname

(或删除换行符。)

于 2012-09-01T05:51:40.003 回答
7

在我开始之前:@John Kugelman 的回答(适当的引用)是解决这个问题的正确方法。设置 noglob 只能解决问题的某些变体,并在此过程中产生其他潜在问题。

但是既然你问了什么set -o noglob,这里是ksh手册页的相关摘录(顺便说一句,你的标签说bash,但错误消息说ksh。我想你实际上是在使用ksh)。

noglob  Same as -f.

-f      Disables file name generation.

File Name Generation.
   Following splitting, each field is scanned for the characters *, ?,  (,
   and  [  unless  the -f option has been set.  If one of these characters
   appears, then the word is regarded as a pattern.  Each file name compo-
   nent  that  contains  any  pattern character is replaced with a lexico-
   graphically sorted set of names that  matches  the  pattern  from  that
   directory.

那是什么意思?这是一个应该显示效果的快速示例:

$ echo *
file1 file2 file3 file4
$ ls *
file1 file2 file3 file4
$ *    # Note that this is equivalent to typing "file1 file2 file3 file4" as a command -- file1 is treated as the command (which doesn't exist), the rest as arguments to it
ksh: file1: not found

现在观察 noglob 集的变化:

$ set -o noglob
$ echo *
*
$ ls *
ls: *: No such file or directory
$ *
ksh: *: not found
于 2012-09-01T07:31:57.950 回答