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

前端 未结 1 1449
-上瘾入骨i
-上瘾入骨i 2021-01-26 07:36

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

Variable

#!/bin/bash

echo Hello \"$who\"
who=\"World\"

1条回答
  •  迷失自我
    2021-01-26 07:56

    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
    

    0 讨论(0)
提交回复
热议问题