0

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
)
7
  • You can't declare and use functions before the definition like you can in C. Why are you trying to do this? Do you just want the functions/variables defined at the end of the script for readability? Commented May 19, 2016 at 23:13
  • @thatotherguy You are correct, I have a heredoc in the script and would like it to be below the command. Commented May 19, 2016 at 23:15
  • I don't follow. Do you have a here doc with variables in it, and you want the variables to be defined further down? Can you just use functions, like main() { echo "Hello $who"; }; ...; who="world"; main ? Commented May 19, 2016 at 23:19
  • @thatotherguy You are correct again, I want variables in the here doc and generally just at the bottom of the command for readability. Both the command and here doc are large... Also to note, I do have vars before the command and I don't want to point to an external doc. Commented May 19, 2016 at 23:33
  • Would using a method like I suggested be an option? There's no way to get around the fact that you have to define functions/variables before they're used, but you can control flow in those kinds of ways Commented May 19, 2016 at 23:45

1 Answer 1

2

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
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.