“set -o noglob” in bash shell script

后端 未结 2 1904
一向
一向 2021-02-11 02:22

I would usually write SQL statements inline in a Bash shell script to be executed in SQLPlus as-

#! /bin/sh

sqlplus user/pwd@dbname<         


        
2条回答
  •  温柔的废话
    2021-02-11 02:59

    After, a bit of digging we realized, using set -o noglob would resolve this issue entirely

    It doesn't resolve the issue so much as it hides it. The issue at hand is the lack of quoting. Quoting variables is usually a good practice as it prevents the shell from doing unexpected things when the variable contains special characters, whitespace, etc.

    Disabling globbing does prevent the * from being expanded, but that's generally not something you want to do. It'll let you use * and ?, but things could break if you used other special characters.

    There are a number of other files in the directory and I am not sure why * chose to execute somefile.sh or is pointed to somefile.sh.

    Here * expands to all of the file names in the current directory, and then this file list becomes the command line. The shell ends up trying to execute whichever file name is first alphabetically.


    So, the right way to fix this is to quote the variable:

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

    That will solve the wildcard problem. The other issue is that you need the \n escape sequence to be interpreted as a newline. The shell doesn't do this automatically. To get \n to work either use echo -e:

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

    Or use the string literal syntax $'...'. That's single quotes with a dollar sign in front.

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

    (Or delete the newline.)

提交回复
热议问题