如何在bash中访问名称中带有空格的环境变量? [英] How can you access an environment variable that has a space in its name in bash?

查看:143
本文介绍了如何在bash中访问名称中带有空格的环境变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行env返回清除工作区= true".如何在bash中访问它?仅供参考,它来自Jenkins Parameterized Build参数名称. ${Clear Workspace}似乎不起作用.

Running env returns "Clear Workspace=true". How can I access it in bash? FYI, it's coming from a Jenkins Parameterized Build parameter name. ${Clear Workspace} does not appear to work.

而且,詹金斯怎么能创建这个环境变量?在bash中运行Clear Workspace=true显然不起作用,因为它尝试使用参数"Workspace = true"来运行"Clear"命令.

Also, how is Jenkins even able to create this environment variable? Running Clear Workspace=true in bash obviously doesn't work as it tries to run the "Clear" command with an argument of "Workspace=true".

我当然可以将作业参数名称设置为Clear_Workspace,但是它以一种形式呈现给用户,所以我宁愿不这样做.另外,用于Jenkins的Maven Build插件具有多个参数名称,其中包含空格,因此必须可以通过某种方式访问​​它们.

I could of course make the job parameter name Clear_Workspace, but it's presented in a form to the user, so I'd rather not. Also, the Maven Build Plugin for Jenkins has several parameter names with spaces in them, so it must be possible to access them somehow.

推荐答案

您可以使用env命令

env Clear\ Workspace=true bash

这将为您提供一个设置了环境变量的shell.

That will give you a shell with the environment variable set.

一种获取环境变量值的骇人方法是:

A hacky way to get the environment variable value back out is:

declare -p Clear\ Workspace | sed -e "s/^declare -x Clear Workspace=\"//;s/\"$//" 

除此之外,您需要使用本机代码程序或脚本语言将其提取出来,例如

Other than that you'd need to use either a native code program or a scripting language to pull it out, e.g.

ruby -e "puts ENV['Clear Workspace']"

哪个更没有hacky ...如果您没有红宝石

Which is much less hacky... also if you don't have ruby

perl -e 'print "$ENV{\"Clear Workspace\"}\n";'

python -c 'import os; print os.environ["Clear Workspace"]'

这是本机代码版本:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv, char **envp) 
{
  char **env;
  char *target;
  int len;
  if (argc != 2) 
  {
    printf("Syntax: %s name\n", argv[0]);
    return 2;
  }
  len = strlen(argv[1]);
  target = calloc(len+2,sizeof(char));
  strncpy(target,argv[1],len+2);
  target[len++] = '=';
  target[len] = '0';
  for (env = envp; *env != 0; env++) 
  {
    char *thisEnv = *env;
    if (strncmp(thisEnv,target,len)==0)
    {
      printf("%s\n",thisEnv+len);
      return 0;
    }
  }
  return 1;
}

这篇关于如何在bash中访问名称中带有空格的环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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