1

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!

2
  • 3
    Consider running your script through shellcheck.net and taking note of the errors. Commented Mar 2, 2022 at 1:23
  • 1
    No white space surrounding =. $foo is not a declaration, if it had a value it would be executed as a command. The if statement logic is fine, assuming you want Jane if the first arg is empty, and John if it isn't. Commented Mar 2, 2022 at 1:55

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.