0

I have shell script as below

query="SELECT * from [myDB.myTable]"
echo $(date +"%Y-%m-%d %H:%M:%S")'|'land'|'Failure'|||'twice'|'$query > test.log

When I run above in some directory in my Unix PC, the test.log shows the result as below

2017-12-13 06:54:03|land|Failure|||twice| SELECT temp1.txt test tmp.log tt.sh from [myDB.myTable]

Actually I wanted query to be redirected as it is in the log file, instead it printed all the file names of that directory.

How can I fix this issue?

Praveen
  • 31
  • 8
  • As I always say, when in doubt ... quote it! – Travis Clarke Dec 13 '17 at 07:07
  • Just put a set of double quotes around the echo expression and you are good! (reference: https://stackoverflow.com/questions/47784319/git-commit-message-messed-up-when-stored-in-a-variable/47784488#47784488) – Travis Clarke Dec 13 '17 at 07:08
  • @TravisClarkeThanks. It works :) – Praveen Dec 13 '17 at 07:22
  • Np. Green check me (i.e. accept answer) and I'll be on my way. lol. But on a serious note, always using double quotes is a good habit! Especially if the expression contains a `*`, `?`, or `[`. – Travis Clarke Dec 13 '17 at 07:23

2 Answers2

0

The dreaded pathname expansion strikes again! You can attribute that list of filenames to having a * in an unquoted expression.

echo "$(date +'%Y-%m-%d %H:%M:%S')'|'land'|'Failure'|||'twice'|'$query" > "test.log"
#    ^                                                                ^  

cat "test.log"
> 2017-12-13 06:54:03|land|Failure|||twice| SELECT * from [myDB.myTable]
Travis Clarke
  • 5,951
  • 6
  • 29
  • 36
0

Use double quotes for your complete echo, the single quotes can be deleted:

echo "$(date +"%Y-%m-%d %H:%M:%S")|land|Failure|||twice|${query}" > test.log

I also have put curly braves in ${query}, that is not a solution for your problem but a good habit for future scripts.

Walter A
  • 19,067
  • 2
  • 23
  • 43