本文介绍了Bash脚本;如何使用命令后定义的vars和funcs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用在命令后定义的变量或函数.

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

变量

#!/bin/bash

echo Hello "$who"
who="World"

功能

#!/bin/bash

function_name

function_name() {
echo Hello World
}

我还听说有一条命令可以在执行任何命令之前读取整个bash脚本,这对于我的情况是适用的.但是,如果有更精确的方法,那就太好了.

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.

更深入

#!/bin/bash

h=Hello

echo $h "$who"

var1=World

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

推荐答案

在使用前必须始终定义变量和函数.这是因为函数定义实际上是在当前上下文中分配名称的命令,与在C中仅提供名称实现的C语言不同.

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

这篇关于Bash脚本;如何使用命令后定义的vars和funcs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 21:21