Bash - 使用特殊字符导出环境变量($)

时间:2017-04-19 12:23:45

标签: bash

我正在使用key=value数据解析文件,然后将它们导出为环境变量。我的解决方案有效,但没有特殊字符,例如:

。数据

VAR1=abc
VAR2=d#r3_P{os-!kblg1$we3d4xhshq7=mf$@6@3l^

script.sh

#!/bin/bash
while IFS="=" read -r key value; do
  case "$key" in
    '#'*) ;;
    *)
      eval "$key=\"$value\""
      export $key
  esac
done < .data

$ . ./script.sh

输出:

$ echo $VAR1
abc
$ echo $VAR2
d#r3_P{os-!kblg1=mf6@3l^

但应该是:d#r3_P{os-!kblg1$we3d4xhshq7=mf$@6@3l^

5 个答案:

答案 0 :(得分:3)

使用反斜杠\

逃避$符号

答案 1 :(得分:3)

您根本不需要 eval ,只需使用declare内置的bash即时创建变量!

case "$key" in
  '#'*) ;;
   *)
       declare $key=$value
       export "$key"
esac

答案 2 :(得分:1)

如果您无法更改 .data 文件,则必须在将值分配给键时转义特殊字符$。将分配行更改为:

eval "$key=\"${value//\$/\\\$}\""

${variable//A/B}表示将A中的每个B实例替换为variable中的struct player{ char name[20]; int time; }s[50];

有关bash变量here

的更多有用信息

答案 3 :(得分:1)

我发现以下脚本(有待提供)很有帮助:

 const [show, setShow] = useState(false);

  

    return (
        <Box align="center">
            <Box pb={2}>
                <Box align="left">
                    <h1>UI Elements</h1>
                </Box>
                <Card>
                    <CardContent>
                        <h2 align = 'Left'><FormatColorFillIcon/> Colors</h2>
                        <hr/>
                        <App/>
                    </CardContent>
                </Card>
                <IconButton onClick={()=> setShow(!show)} aria-label="Hello sir" align = "right">
                <CodeIcon/>
                </IconButton>
                { show ? 
                    <div><Paper className = {classes.paperColor}>
                            <SyntaxHighlighter classes = {classes.paperColor} language="javascript" style={docco} align = "left" style = {dracula}> 
                                {codeString}
                            </SyntaxHighlighter>
                        </Paper>
                    </div> : null}

来自:https://stackoverflow.com/a/66118031/339144

答案 4 :(得分:0)

只需使用单引号:

export VAR2='d#r3_P{os-!kblg1$we3d4xhshq7=mf$@6@3l^'
相关问题