Método 1:
Oneliner:
s="hello"
for ((i=0;i<${#s};i++)); do result[$i]="${s:i:1}"; done
echo ${result[@]}
Código expandido:
s="hello" # Original string.
for ((i=0;i<${#s};i++)); do # For i=0; i<(length of s); i++
result[$i]="${s:i:1}" # result[i] is equal to the i th character of $s
done # End of the loop
echo ${result[@]} # Print all elements of $result.
Método 2:
Oneliner:
s="hello"
var=($(while read -n 1; do printf "$REPLY "; done <<< "$s"))
echo "${var[@]}"
Código expandido:
s="hello" # Original string.
while read -n 1; do # Read chraracter by character the string.
space_separated=$(printf "$space_separated $REPLY") # $space_separated is equal to it plus the current character.
done <<< "$s" # Pass the string to the loop
result=($space_separated) # Split $space_separated into an array.
echo "${result[@]}" # Print all elements of $result.
Agradecemos a @cuonglm por sua sugestão.
Efetivamente, você pode usar $REPLY
, que é o padrão onde read
lê a entrada.