0

I have an existing script in my Linux host with these statements:

local variable=$1
if [ "z${variable}" != "zfalse" ]; then
  local flag="--some_flag"
fi

I haven't found an explanation of these "z${variable}" and "zfalse" notation or syntax in my Shell Scripting book. Hope someone can help explain what they mean. Thanks in advance.

melpomene
  • 84,125
  • 8
  • 85
  • 148
H. Lefty
  • 3
  • 2
  • 1
    Do you know what `echo "Hello"` does? How about `echo "zfalse"`? – melpomene Sep 15 '18 at 00:40
  • Yes. zfalse is not an explicitly defined string in the script. echo "zfalse" returns zfalse. – H. Lefty Sep 15 '18 at 00:43
  • What do you mean by "explicitly defined string"? How do you define a string? – melpomene Sep 15 '18 at 00:44
  • function run_function { local param=$1 local variable=$2 if [ "z${variable}" != "zfalse" ]; then local flag="--some_flag" fi … } run_function “string 1” false … run_function “string 2” … – H. Lefty Sep 15 '18 at 01:03
  • You can't. Why do you want to put a newline in the comment field? – melpomene Sep 15 '18 at 01:07
  • 2
    Possible duplicate of [Why do shell script comparisons often use x$VAR = xyes?](https://stackoverflow.com/q/174119/608639), [Bash test for empty string with X](https://stackoverflow.com/q/6852612/608639), [Portable way to check emptyness of a shell variable](https://stackoverflow.com/a/24900088/608639), etc. – jww Sep 15 '18 at 01:10

1 Answers1

0

'z' is there to prevent syntax error in case ${variable} evaluates to nothing. If your user does not provide $1 parameter, ${variable} is empty, and without 'z', the if condition would look something like

if [ != false ] ...

which is syntactically incorrect. With 'z', it becomes:

if [ z != zfalse ] ...
Dejan D.
  • 81
  • 5
  • 1
    That's incorrect. The variable is quoted, so `[ "${variable}" != "false" ]` would work fine even with empty variables. – melpomene Sep 15 '18 at 01:10
  • 1
    @melpomene It's useless today, but the pattern was useful decades ago when some shells handled `""` incorrectly. – John Kugelman Sep 15 '18 at 01:22
  • 1
    The number of decades we're talking about is relevant. Correct behavior was standard-mandated in 1992, and widespread well before that. – Charles Duffy Sep 15 '18 at 01:26