【问题标题】:How can I disable * expansion in a script?如何在脚本中禁用 * 扩展?
【发布时间】:2020-06-09 12:15:15
【问题描述】:

我有一个奇怪的问题 - 可能我只是失明了。我有这个简短的脚本,它将 here-document 中的字符串 #qry# 替换为文件中的 select 语句,然后将其通过管道传输到 mysql:

#!/bin/bash

if [[ "$1" == "-h" ]]
then
  echo "sqljob [sqlfile] [procnm] [host] [database] [config file]"
  echo "       sqlfile: text file containing an SQL statement"
  echo "       procnm: name that will given to the new, stored procedure"
  echo "       host: hostname of IP address of the database server"
  echo "       database: the procedure will be created here"
  echo "       config file: default configuration file with username and password"
  exit
fi

infile=$1
procnm=$2
hn=$3
pn=$4
db=$5
mycfg=$6

{
set -o noglob
sed -e "s/#qry#/$(echo $(cat $infile))/g" <<!
drop procedure if exists $procnm;
delete from jobs where jobname="$procnm";

insert into jobs
set
  notes="SQL job $procnm",
  jobname="$procnm",
  parm_tmpl='int';

delimiter //
create procedure $procnm(vqid int)
begin
  call joblogmsg(vqid,0,"$procnm","","Executing #qry#");
  drop table if exists ${procnm}_res;
  create table ${procnm}_res as
  #qry#
end//
delimiter ;
!
} | mysql --defaults-file=$mycfg -h $hn -P $pn $db

但是,当select 包含* 时,它会扩展到目录中的任何内容即使我使用noglob。但是,它可以从命令行运行:

$ set -o noglob
$ ls *

我做错了什么?

编辑

Block Comments in a Shell Script 已被建议为重复,但您会注意到,我需要在 here-doc 中扩展 ${procnm};我只需要避免select * 发生同样的事情。

【问题讨论】:

  • 这能回答你的问题吗? Block Comments in a Shell Script
  • 在输入结束标记周围使用单引号。 unix.stackexchange.com/questions/68419/…
  • 并停止编写安全漏洞。永远不要通过连接构建 SQL 语句!请改用准备好的语句。
  • $(echo $(cat $infile)) 是对回显的无用使用。请注意,它被字符串 verbatim 替换,它不会被执行。 when the select contains * 您的脚本中没有“选择”变量。什么包含*?如何重现您的问题?也许不是问 XY 问题——你真正想要做什么?要在end// 之前输出文件infille 的内容吗?而且您不导出 shell 选项,set -o noglob 仅适用于当前 shell。
  • @ceving 我是否把我的陈述写成这样对你有什么影响?我已经考虑了安全隐患,在这种情况下,我认为风险很小。

标签: bash


【解决方案1】:

我怀疑这是因为构造 echo (cat)。 echo 命令从 cat 命令中获取 *,然后运行它的 shell 扩展它。在那个 shell 中,noglob 是不活动的。

试着留下回声:/$(cat $infile)/,最后就是你需要的数据;那么shell就没有额外的glob扩展了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 2020-03-27
    • 2010-09-13
    • 1970-01-01
    • 2019-07-01
    相关资源
    最近更新 更多