First, you have an extra dollar sign (shown in red above) that shouldn't be there.
Second: your default if empty
string is misleading. With the form argument=${parm-word}
, word is assigned only if parm is unset. If parm is set, but empty; argument
will be set to the empty string.
To get what you probably intended (assign word if parm is set to an empty string or if parm is unset); you want:
argument=${1:-"default if unset or empty"}
If I understand what you're trying to do (assign an awk
variable the value of a shell variable
if it is set and not empty, the easy way is to still use shell variable assignment:
awk -v argument=${1:-"default if unset or empty"} 'BEGIN{print argument}'
But, you can also do it entirely inside an awk
script. Compare what happens with the following script:
#!/bin/ksh
date > now
awk -v v1="v1 -v" '
function setvars() {
v1 = v1 ? v1 : "v1 unset, empty string, or 0"
sub("^$", "v2 is unset or empty string", v2)
printf("fn=%d, FILENAME=\"%s\"\nv1=\"%s\"\nv2=\"%s\"\n\n",
fn, FILENAME, v1, v2)
}
BEGIN { setvars()
}
FNR == 1 {
fn++
setvars()
print fn, $0
print ""
}
END { print "in END clause"
setvars()
}' v2='v2 before 1st file operand' now v1= v2= now v1=0 v2=0 now v1=abc \
v2=def now v1='v1 after last file operand' v2=0
which, with any POSIX conforming shell such as bash
or ksh
(it has been tested with both) produces the output:
fn=0, FILENAME=""
v1="v1 -v"
v2="v2 is unset or empty string"
fn=1, FILENAME="now"
v1="v1 -v"
v2="v2 before 1st file operand"
1 Thu Apr 30 20:54:59 PDT 2015
fn=2, FILENAME="now"
v1="v1 unset, empty string, or 0"
v2="v2 is unset or empty string"
2 Thu Apr 30 20:54:59 PDT 2015
fn=3, FILENAME="now"
v1="v1 unset, empty string, or 0"
v2="0"
3 Thu Apr 30 20:54:59 PDT 2015
fn=4, FILENAME="now"
v1="abc"
v2="def"
4 Thu Apr 30 20:54:59 PDT 2015
in END clause
fn=4, FILENAME="now"
v1="v1 after last file operand"
v2="0"
If you want to try this on a Solaris/SunOS system, change awk
to /usr/xpg4/bin/awk
.