0

I have been trying to split up a string and putting it into an Array in Bash on my Mac without success.

Here is my sample code:

#!/bin/bash
declare -a allDisks
allDisksString="`ls /dev/disk* | grep -e 'disk[0-9]s.*' | awk '{ print $NF }'`"
#allDisksString="/dev/disk0s1 /dev/disk1s1"
echo allDisksString is $allDisksString
IFS=' ' read -ra allDisks <<< "$allDisksString"
echo allDIsks is "$allDisks"
echo The second item in allDisks is "${allDisks[1]}"
for disk in "${allDisks[@]}"
do
    printf "Loop $disk\n"
done

And below is the output:

allDisksString is /dev/disk0s1 /dev/disk0s2 /dev/disk0s3 /dev/disk0s4 /dev/disk1s1
allDIsks is /dev/disk0s1
The second item in allDisks is 
Loop /dev/disk0s1

Interesting if I execute the following in the Mac Terminal:

ls /dev/disk* | grep -e 'disk[0-9]s.*' | awk '{ print $NF }'

I get the following output

/dev/disk0s1
/dev/disk0s2
/dev/disk0s3
/dev/disk0s4
/dev/disk1s1

So I have also tried setting IFS to IFS=$'\n' without any success.

So no luck in getting a list of my drives into an array.

Any ideas on what I am doing wrong?

2 Answers 2

2

You're making this much more complicated than it needs to be. You don't need to use ls, you can just use a wildcard to match the device names you want, and put that in an array assignment.

#!/bin/bash

declare -a allDisks
allDisks=(/dev/disk[0-9]s*)
echo allDIsks is "$allDisks"
echo The second item in allDisks is "${allDisks[1]}"
for disk in "${allDisks[@]}"
do
    printf "Loop $disk\n"
done
Sign up to request clarification or add additional context in comments.

2 Comments

P.S. There is an small error in your code that was carried over from my code. The third line in your code above really should be: echo allDIsks is "${allDisks[*]}"
It's only an error if you really intended to print the whole array.
0

read only reads one line.

Use an assignment instead. When assigning to an array, you need to use parentheses after the = sign:

#!/bin/bash
disks=( $(ls /dev/disk* | grep -e 'disk[0-9]s.*' | awk '{ print $NF }') )
echo ${disks[1]}

Comments

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.