简体   繁体   English

在Bash脚本中传递变量名称和值

[英]Pass Variable Name and Value in Bash Script

I just want to verify that the script I wrote is doing what I think it's doing, and that it's doing it properly. 我只想验证我编写的脚本是否正在执行我认为正在执行的操作,并且是否正确执行了该操作。

I wanted to write a script that takes an environment variable and a string value, and then sets that variable to the given value. 我想编写一个脚本,该脚本需要一个环境变量和一个字符串值,然后将该变量设置为给定值。 So I can do something like setvar BOOST_HOME /home/me/boost/boost_1.52.0 and the script will export BOOST_HOME=/home/me/boost/boost_1.52.0 所以我可以做一些类似setvar BOOST_HOME /home/me/boost/boost_1.52.0的脚本,脚本将export BOOST_HOME=/home/me/boost/boost_1.52.0

Something like: 就像是:

#!/bin/bash
# Usage: setvar VAR VAR_VALUE
function setvar()
{
    VAR=${1}
    VAR_VALUE=${2}
    if [ -d $2 ]
    then
        eval export $VAR=$2
    fi
}

This seems to work, at least judging from a echo echo tests, but I am still not very comfortable with shell scripting, and would like someone to either verify what I am doing or point out what I am doing wrong / less correct. 至少从回声echo测试来看,这似乎可行,但我对shell脚本仍然不太满意,并且希望有人可以验证我在做什么,或者指出我在做错/不太正确。

You don't need the eval. 您不需要评估。

setvar() {
  if [[ -d $2 ]]; then
    export "$1=$2"
  fi
}

Using [[ instead of [ avoids the need to quote $2 , since the bash (and other shell) extension [[ does not word-split interior parameter expansions. 使用[[而不是[可以避免引用$2 ,因为bash(和其他shell)扩展名[[不会对内部参数扩展进行单词分割。 If I'd stuck with the old-fashioned [ -d "$2" ] , I would have had to quote the $2 in case its value included whitespace. 如果我坚持使用老式的[ -d "$2" ] ,则必须引用$2以防其值包含空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM