1

Do you know why below shell script just generates the output file named 'Loading_EMP.sql' instead of 'Loading_1_EMP.sql'?

#!/bin/bash

JOBID="1"
TABLE="EMP"

echo 'test'  > Loading_$JOBID_$TABLE.sql; 

# Output
Loading_EMP.sql

# Expected Output
Loading_1_EMP.sql
Mureinik
  • 297,002
  • 52
  • 306
  • 350
Sigularity
  • 917
  • 2
  • 12
  • 28
  • 1
    Possible duplicate of [variable interpolation in shell](http://stackoverflow.com/questions/17622106/variable-interpolation-in-shell) – jackrabbit Jul 30 '16 at 08:07
  • @jackrabbit : Apart from the variable interpolation issue, there is also an issue of missing double quotes – sjsam Jul 30 '16 at 08:32

3 Answers3

3
echo 'test'  > Loading_${JOBID}_${TABLE}.sql; 

should do it, or better

echo 'test'  > "Loading_${JOBID}_${TABLE}.sql" # to avoid word splitting

In Loading_$JOBID_$TABLE, shell trates $JOBID_ as a single variable and since it is not set, it substitutes $JOBID_ with nothing resulting in Loading_EMP.sql


This [ answer ] must read for you.

Community
  • 1
  • 1
sjsam
  • 21,411
  • 5
  • 55
  • 102
1

The interpreter thinks you are referring to a variable named JOBID_. Enclose the name with {}.

echo 'test'  > Loading_${JOBID}_$TABLE.sql
jackrabbit
  • 5,525
  • 1
  • 27
  • 38
  • 1
    You might consider double quoting `Loading_${JOBID}_$TABLE.sql` to accommodate filenames with spaces. – sjsam Jul 30 '16 at 08:31
  • Those only matter if you have spaces or other weird characters. His script clearly does not suffer from that. – jackrabbit Jul 30 '16 at 10:25
1

_ is not a special character in shell. So the shell sees this as you echoing a $JOBID_ variable, which is undefined, and thus empty. Instead, you should explicitly show the shell what your variables are by using {}:

echo 'test'  > Loading_${JOBID}_${TABLE}.sql;
# Here -----------------^-----^--^-----^
Mureinik
  • 297,002
  • 52
  • 306
  • 350