-1

I'm trying to create a SQL Query and trying to assign it to some variable but I couldn't do that.

TABLENAME=foo
QUERY="select * from $TABLENAME"
echo $QUERY

I'm expecting the Query would be select * from foo

Instead of that I'm getting select [file names in the directory] from foo

Here is exactly what I'm getting instead of getting the Original Query.

select Anaconda3-5.3.1-Linux-x86_64.sh hadoop-2.7.3 hadoop-2.7.3.tar.gz script.sh from foo

2

You have to quote your variable:

echo "$QUERY"

Otherwise the shell expands the * to the files in the current directory.

Try echo "*" and echo * in your shell.

The * is part of a feature of your shell (probably Bash) called Pathname Expansion.

From the bash man page:

The special pattern characters have the following meanings:

*      Matches any string, including the null string.  When the globstar  shell  option
       is  enabled, and * is used in a pathname expansion context, two adjacent *s used
       as a single pattern will match all files and zero or more directories and subdi-
       rectories.   If followed by a /, two adjacent *s will match only directories and
       subdirectories.

To prevent this you can escape the * with a backslash \, or quote it with double quotes " or single quotes '

Example:

# no pathname expansion
$ echo \*
*
$ echo "*"
*
$ echo '*'
*

# pathname expansion
$ echo *
file_x file_y file_z_in_this_directory

The problem with single quotes is, that it would prevent the expansion of your variables (also called parameter expansion). All characters are interpreted literally.

# no variable expansion
$ echo '$QUERY'
$QUERY

# variable expansion
$ echo "$QUERY"
select * from foo

# variable expansion and pathname expansion
$ echo $QUERY
select file_x file_y file_z_in_this_directory from foo
  • Yes it Works !!! Thanks Freddy ! Please tell me, how it works and why that was not working ? – Parvathi Rajan Apr 18 at 19:00
  • @ParvathiRajan Added a short explanation. – Freddy Apr 18 at 19:49
  • @ParvathiRajan You should (almost) always double-quote variable references in a shell script. This is only one of the things that can go wrong when they're not double-quoted. – Gordon Davisson Apr 19 at 6:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.