Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Quote all the value of an array as text

I have the following array:

arr1=("a" "b" "c" "d" "e" "f")

and I want to display the array as quote. So my expected output from echo would be this:

AA_ENABLE_HOOKS=("a" "b" "c" "d" "e" "f")

I have done the following code it almost display what I want but I don’t like it:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#!/bin/bash

arr1=("a" "b" "c" "d" "e" "f")

var_quote=$( printf "\"%s\" " "${arr1[@]}")

echo "AA_ENABLE_HOOKS=(${var_quote})"

The output is

AA_ENABLE_HOOKS=("a" "b" "c" "d" "e" "f" ) // notice I have space at the end

Is there alternative for my above code in bash?

My current workaround for one-liner command is:

echo "AA_ENABLE_HOOKS=($( printf "\"%s\" " "${arr1[@]}" | sed -e 's/\ *$//g'))"

>Solution :

To remove the space at the end of the output string, you can use the ${var_quote% } syntax, which removes the trailing space character from the $var_quote variable.

Here is an updated version of your script that uses this syntax:

#!/bin/bash

arr1=("a" "b" "c" "d" "e" "f")

var_quote=$( printf "\"%s\" " "${arr1[@]}")

# Remove the trailing space character from $var_quote
var_quote=${var_quote% }

echo "AA_ENABLE_HOOKS=(${var_quote})"

This should produce the output AA_ENABLE_HOOKS=("a" "b" "c" "d" "e" "f") without the space at the end.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading