Home > Software design >  Decoupling variable declaration and assignment in bash
Decoupling variable declaration and assignment in bash

Time:03-03

Bash here. I want to write a script that declares several variables, assigns them different values based on a conditional, and then uses them later on (whatever they were conditionally assigned to):

#!/usr/bin/bash
$fizz
$buzz
$foo
if [ -z "$1" ]
then
  fizz = "Jane Smith"
  buzz = true
  foo = 44
else
  fizz = "John Smith"
  buzz = false
  foo = 31
fi

# now do stuff with fizz, buzz and foobar regardless of what their values are

When I run this (bash myscript.sh) I get errors. Can anyone spot if I have a syntax error anywhere? Thanks in advance!

CodePudding user response:

There are a few problems with your script:

  1. a line with just $variable is not a declaration. That will be evaluated and expanded to an empty line (since your variables don't exist).

  2. Bash does not allow spaces around the = sign

On declaring variables, you don't really need to do that, since bash won't give you an error if an variable doesn't exist - it will just expand to an empty string. If you really need to, you can use variable= (with nothing after the =) to set the variable to an empty string.

I'd suggest changing it to this:

#!/usr/bin/env bash

if [ -z "$1" ]
then
  fizz="Jane Smith"
  buzz=true
  foo=44
else
  fizz="John Smith"
  buzz=false
  foo=31
fi

By the way, keep in mind that bash has no concept of variable types - these are all strings, including false, true, 44, etc.

  •  Tags:  
  • bash
  • Related