SongJaeGu SongJaeGu - 6 months ago 13
Linux Question

Bash script; how to use vars and funcs defined after command

How to use variables or functions that are defined after the command.

Variable

#!/bin/bash

echo Hello "$who"
who="World"


Function

#!/bin/bash

function_name

function_name() {
echo Hello World
}


I also heard there is a command to read entire bash script before executing any commands, this would work for my case. But it would be nice if there is a more pinpoint way.

More in-depth

#!/bin/bash

h=Hello

echo $h "$who"

var1=World

who=$(cat <<HEREDOC
You
Me
$var1
HEREDOC
)

Answer

Variables and functions always have to be defined before use. This is because function definitions are actually commands that assign the name in the current context, and not like in C where they merely provide an implementation for a name.

You can instead use control flow to ensure that the definitions execute before your code, regardless of their relative layout in the file:

main() {
  echo "Hello $var"
}

var="world"
main
Comments