使用bash从ubuntu上的文件中读取带有未转义字符的环境变量

编程入门 行业动态 更新时间:2024-10-27 13:29:22
本文介绍了使用bash从ubuntu上的文件中读取带有未转义字符的环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

如何在 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-29 07:42:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1186690.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符   环境变量   文件   bash   ubuntu

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!