Home > Back-end >  How to reuse an ANSI-C quoting variable in another Bash command?
How to reuse an ANSI-C quoting variable in another Bash command?

Time:11-26

I'm trying to figure out how to use a variable containing an ANSI-C quoting string as an argument for a subsequent bash command. The string in the variable itself is a list of files (can virtually be a list of anything).

For example, I have a file containing a list of other files, for example test.lst containing :

  >$ cat test.lst
a.txt
b.txt
c.txt

I need to pass the file content as a single string so I'm doing : test_str=$(cat test.lst) then converts to ANSI-C quoting string: test_str=${test_str@Q}

So at the end I have :

  >$ test_str=$(cat test.lst)
  >$ test_str=${test_str@Q}
  >$ echo $test_str
$'a.txt\nb.txt\nc.txt'

which is what I'm looking for.

Then problem arises when I try to reuse this variable as a string list in another bash command. For example direct use into a for loop :

  >$ for str in $test_str; do echo $str; done
$'a.txt\nb.txt\nc.txt'

What I expect at this step is that it prints the same thing as the content of the original test.lst

I also tried expanding it back but it leaves leading $' and trailing '

  >$ str=${test_str@E}
  >$ echo $str
$'a.txt b.txt c.txt'

I also tried printf and some other stuffs to no avail. What is the correct way to use such ANSI-C quoting variable into a bash command ?

CodePudding user response:

In the first place, why do you need quoting? Just keep the data untouched stored as elements of an array:

mapfile -t filelist < test.lst
# iterate through the list
for file in "${filelist[@]}"; do printf '%s\n' "$file"; done

CodePudding user response:

How about:

eval echo "${test_str}"

I believe that an ANSI-C quoted string is meant to be evaluated by bash command line parser.

  • Related