2

If i have an array like

arr[0]=2019-06-26
arr[1]=15:21:54

How can i convert that into a string whose value is

'2019-06-26 15:21:54'
7

If the first character of IFS variable is a space (which it is by default), you can use the star index in double quotes.

#! /bin/bash
arr[0]=2019-06-26
arr[1]=15:21:54

string="${arr[*]}"
printf "'%s'" "$string"

Documented under Special Parameters:

When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable.

3

For completeness, while the "${array[*]}" Korn syntax (extended from the Bourne "$*" special parameter) would also work in zsh, in zsh, you may want to use the j (for join) parameter expansion flag instead which allows you to use any arbitrary joining string and doesn't need to rely on a global parameter like $IFS:

$ a=(foo bar)
$ echo ${(j[:::])a}
foo:::bar

Note that for "${a[*]}", ksh (both ksh93 and mksh) join on the first byte of $IFS instead of first character. That matters for multi-byte characters like:

$ ksh -c 'a=(foo bar); IFS="⇅"; echo "${a[*]}"'
foo�bar
$ mksh -c 'a=(foo bar); IFS="⇅"; echo "${a[*]}"'
foo�bar
$ mksh -o utf8-mode -c 'a=(foo bar); IFS="⇅"; echo "${a[*]}"'
foo�bar

(where that is how my terminal emulator rendered the first byte (0xe2) of that character which by itself doesn't form a valid character).

Other Korn-like shells with array support are OK:

$ bash -c 'a=(foo bar); IFS="⇅"; echo "${a[*]}"'
foo⇅bar
$ zsh -c 'a=(foo bar); IFS="⇅"; echo "${a[*]}"'
foo⇅bar
$ yash -c 'a=(foo bar); IFS="⇅"; echo "${a[*]}"'
foo⇅bar

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.