如何使用 Bash 引用变量的文件? [英] How to reference a file for variables using Bash?

查看:31
本文介绍了如何使用 Bash 引用变量的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为一个变量调用一个设置文件,我该如何在 bash 中做到这一点?

I want to call a settings file for a variable, how can I do this in bash?

因此设置文件将定义变量(例如:CONFIG.FILE):

So the settings file will define the variables (eg: CONFIG.FILE) :

production="liveschool_joe"
playschool="playschool_joe"

脚本会在其中使用这些变量

And the script will use those variables in it

#!/bin/bash
production="/REFERENCE/TO/CONFIG.FILE"
playschool="/REFERENCE/TO/CONFIG.FILE"
sudo -u wwwrun svn up /srv/www/htdocs/$production
sudo -u wwwrun svn up /srv/www/htdocs/$playschool

我怎样才能让 bash 做这样的事情?我是否必须使用 awk/sed 等...?

How can I get bash to do something like that? Will I have to use awk/sed etc...?

推荐答案

简答

使用 source 命令.

例如:

#!/usr/bin/env bash
production="liveschool_joe"
playschool="playschool_joe"
echo $playschool

script.sh

#!/usr/bin/env bash
source config.sh
echo $production

注意本例中 sh ./script.sh 的输出是:

Note that the output from sh ./script.sh in this example is:

~$ sh ./script.sh 
playschool_joe
liveschool_joe

这是因为 source 命令实际上运行了程序.config.sh 中的所有内容都会被执行.

This is because the source command actually runs the program. Everything in config.sh is executed.

您可以使用内置的 export 命令,获取和设置环境变量"也可以实现这一点.

You could use the built-in export command and getting and setting "environment variables" can also accomplish this.

运行 exportecho $ENV 应该是你需要知道的关于访问变量的全部内容.访问环境变量的方式与访问局部变量的方式相同.

Running export and echo $ENV should be all you need to know about accessing variables. Accessing environment variables is done the same way as a local variable.

要设置它们,请说:

export variable=value

在命令行.所有脚本都可以访问此值.

at the command line. All scripts will be able to access this value.

这篇关于如何使用 Bash 引用变量的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆