5

I have taken input from user into array. But I need to use them as comma separated list. How can I do that? Input in my case is path like (/usr/tmp/). I appreciate your help and time. Thank you !

Example:

read "Number of subdirectories : " count
for i in $(seq 1 $count)
do
    read -e -p " Subdir : $i: " arr[$i]
done

Expected Result:

$var = {arr[1],arr[2],arr[3],......}
0

1 Answer 1

9

If you have an array like this:

$ declare -p arr
declare -a arr='([1]="abc" [2]="def")'

You can display it in comma-separated format:

$ (IFS=,; echo "{${arr[*]}}")
{abc,def}

That output can be saved in a shell variable using command substitution:

$ var=$(IFS=,; echo "{${arr[*]}}")
$ echo "$var"
{abc,def}
Sign up to request clarification or add additional context in comments.

9 Comments

Thanks @John. I tried but it's not working. I got an error like No such file or directory.
@Rock26 Which command produced an error? Also please let me see the complete exact error message. (Don't retype: copy-and-paste it from you terminal to here.)
Sure../count_lines.sh: line 22: ={plugme/web/,plugme/modules/}: No such file or directory
@Rock26, if you want help with your script, include your script in the question. It is very difficult to diagnose things at this distance.
@Rock26 The command that I showed in the answer was var=$(IFS=,; echo "{${arr[*]}}"). The command that you say you ran was $(IFS=,; echo "{${dir_exclude[*]}}"). Those are two very different commands and they produce two very different results.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.