当前位置: 动力学知识库 > 问答 > 编程问答 >

bash - Escape special characters while sourcing a file

问题描述:

I have a file with the following contents -

a=hello

b='hi'

c=['hi', 'hello']

I want to source the contents of the file. But I get the following error -

-bash: hello]: command not found

How do I escape the special characters?

网友答案:

Version 1: No bash arrays

I think what you are looking for is the declare command. For example, with your definitions in the file file:

$ cat file
a=hello
b='hi'
c=['hi', 'hello']

Let's run declare on each line of your file:

$ while read -r line; do declare "$line"; done <file

We can verify that the definitions were successful and that the environment variables were created by using the -p option:

$ declare -p a b c
declare -- a="hello"
declare -- b="'hi'"
declare -- c="['hi', 'hello']"

Or, using them in an echo statement:

$ echo "a=$a b=$b c=$c"
a=hello b='hi' c=['hi', 'hello']

Unlike sourcing, declare does not execute your file. This makes it much safer to use.

Using this approach, the c variable is a string.

Version 2: bash arrays

This code attempts to parse your assignments and make variables into arrays were appropriate:

#!/bin/bash
while read -r line
do
  case "$line" in
      *[*)
          line=${line/[/(}
          line=${line/]/)}
          line=${line//,/ }
          declare -a "$line"
          ;;
      *)
          declare "$line"
          ;;
  esac
done <file

After this code is run, c is an actual bash array:

$ declare -p a b c
declare -- a="hello"
declare -- b="'hi'"
declare -a c='([0]="hi" [1]="hello")'
网友答案:

The usage is incorrect. If it is that you want to initialize c with an array, you can do it as follows.

cat test
a=hello
b='hi'
c= ('hi' 'hello') 

source test will not give any error. you can use the bellow command to see the content of c

 echo ${c[@]}

which gives the below output

 hi hello
分享给朋友:
您可能感兴趣的文章:
随机阅读: