jhfrontz
jhfrontz

Reputation: 1375

How to keep single quotes from confusing ksh -n

So I have a simple shell script called try.sh:

#! /bin/ksh

echo "'" | awk '

/'\''/ {
print "'\''ello, world"
}
'

and it runs fine:

$ ./try.sh  
'ello, world

But ksh -n is not altogether happy with it:

$ ksh -n ./try.sh
./try.sh: warning: line 3: ' quote may be missing
./try.sh: warning: line 5: ' quote may be missing

I can use tricks (awk variables, awk hex sequences, etc.) to make this go away, but surely there's some native elegant way to appease the ksh syntax checker (if nothing else, for the case when the embedded language has no provision for workarounds). What am I forgetting?

[update: apparently the syntax checker is flagging the line because a quoted string with embedded newline is followed by another quoted string with no intervening white space. David Korn says that he'll be reviewing the check for the next version of ksh. See the ast-users mailing list archives for details.]

Upvotes: 1

Views: 1842

Answers (1)

Henk Langeveld
Henk Langeveld

Reputation: 8446

Here's a minimal snippet of code. IMO, passing a quote char in a variable is the most elegant way out of a nasty problem, as it avoids the quote/unquote pattern, and the awk code you see is the same as what awk gets to process.

$ echo "'" | 
   awk -v q=\'  'q { print q"Hello, world"q }'
'Hello, world'

The original question uses what I call the quote/unquote pattern, which is used a lot with other languages embedded in the unix shell.

The trick presents awk with a series of concatenated quoted and unquoted strings from the shell that together form a valid awk program text. This makes code very hard to maintain, because you as a programmer, cannot see the valid awk code anymore.

Passing the special characters as variables to awk avoids this pattern.

Upvotes: 1

Related Questions