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:
#!/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'))"
CodePudding user response:
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.