使用bash从ubuntu上的文件中读取带有未转义字符的环境变量 [英] Read env variable with unescaped characters from file on ubuntu with bash

查看:31
本文介绍了使用bash从ubuntu上的文件中读取带有未转义字符的环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 bash 中读取包含空格和可能需要转义的其他字符的环境变量?

How to read environmental variable in bash that contains spaces and possibly other characters that need to be escaped?

我有一个文件 server.env

I have a file server.env

PUBLIC_KEY=ssh-rsa whatever+whatever+8whatever/whatever+p+whatever user@alans-MacBook-Pro.local

我正在尝试将此文件作为环境变量读入 bash 脚本:

I am trying to read this file into bash script as an environmental variable:

export $(cat server.env | xargs)

我收到一个错误:

-bash: export: `user@alans-MacBook-Pro.local': not a valid identifier

好的,尝试引用 server.env 中的值:

OK, trying to quote the value in server.env:

PUBLIC_KEY='ssh-rsa whatever+whatever+8whatever/whatever+p+whatever user@alans-MacBook-Pro.local'

  • 同样的错误
  • 双引号:

    PUBLIC_KEY="ssh-rsa whatever+whatever+8whatever/whatever+p+whatever user@alans-MacBook-Pro.local"
    

    • 还有错误
    • 我在这里遗漏了什么?

      推荐答案

      Bash 提供了参数扩展和子字符串删除,这将允许您分离读取的 NAME=value 对从 server.env 文件,然后 export NAME=value 对.

      Bash provides parameter expansion with substring removal that will allow you to separate the NAME=value pairs read from the server.env file and then export the NAME=value pairs.

      您只需要一个简单的读取循环:

      A simple read loop is all you need:

      #!/bin/bash
      
      while read -r line; do              ## read each line of server.env
          val="${line#*=}"                ## trim to 1st =, save in val
          export ${line%=$val}="$val"     ## remove =$val leaving name, export val with name
      done < server.env
      
      printf "%s\n" "$PUBLIC_KEY"         ## confirm
      

      示例使用/输出

      $ bash test.sh
      ssh-rsa whatever+whatever+8whatever/whatever+p+whatever user@alans-MacBook-Pro.local
      

      基本的参数扩展在哪里:

      ${var#pattern}      Strip shortest match of pattern from front of $var
      ${var##pattern}     Strip longest match of pattern from front of $var
      ${var%pattern}      Strip shortest match of pattern from back of $var
      ${var%%pattern}     Strip longest match of pattern from back of $var
      

      (注意: pattern 可以包含普通的 shell glob,如 '*''?')

      (note: pattern can contain normal shell globs like '*' and '?')

      实际上有许多有用的参数扩展可用于字符串操作.只需检查 参数扩展" 标题下的 man bash.

      There are literally dozens of useful parameter expansions you can use for string manipulations. Just check man bash under the "Parameter Expansion" heading.

      这篇关于使用bash从ubuntu上的文件中读取带有未转义字符的环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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