gawk: Shell Quoting
1
1 10.2.9 Quoting Strings to Pass to the Shell
1 -------------------------------------------
1
1 Michael Brennan offers the following programming pattern, which he uses
1 frequently:
1
1 #! /bin/sh
1
1 awkp='
1 ...
1 '
1
1 INPUT_PROGRAM | awk "$awkp" | /bin/sh
1
1 For example, a program of his named 'flac-edit' has this form:
1
1 $ flac-edit -song="Whoope! That's Great" file.flac
1
1 It generates the following output, which is to be piped to the shell
1 ('/bin/sh'):
1
1 chmod +w file.flac
1 metaflac --remove-tag=TITLE file.flac
1 LANG=en_US.88591 metaflac --set-tag=TITLE='Whoope! That'"'"'s Great' file.flac
1 chmod -w file.flac
1
1 Note the need for shell quoting. The function 'shell_quote()' does
1 it. 'SINGLE' is the one-character string '"'"' and 'QSINGLE' is the
1 three-character string '"\"'\""':
1
1 # shell_quote --- quote an argument for passing to the shell
1
1 function shell_quote(s, # parameter
1 SINGLE, QSINGLE, i, X, n, ret) # locals
1 {
1 if (s == "")
1 return "\"\""
1
1 SINGLE = "\x27" # single quote
1 QSINGLE = "\"\x27\""
1 n = split(s, X, SINGLE)
1
1 ret = SINGLE X[1] SINGLE
1 for (i = 2; i <= n; i++)
1 ret = ret QSINGLE SINGLE X[i] SINGLE
1
1 return ret
1 }
1