LinuxQuestions.org
Review your favorite Linux distribution.
Go Back   LinuxQuestions.org > Blogs > HMW
User Name
Password

Notices


Rate this Entry

Bash arrays as Python lists (sort of)

Posted 08-08-2015 at 12:38 PM by HMW
Updated 08-08-2015 at 12:44 PM by HMW

If you have some experience with higher level programming languages (such as Python for instance), you have undoubtedly came across lists and arrays.

There are arrays in Bash too, but there is a pitfall when you delete items from an array in Bash; the index disappears with the item!

First, consider this example with a list in Python:
Code:
>>> myList = ['foo', 'bar', 'baz']
>>> myList
['foo', 'bar', 'baz']
>>> del myList[0] # Delete first item
>>> myList
['bar', 'baz']
>>> myList[0]
'bar'
As you can see, even though we delete the first item myList[0], we can still access myList[0], which now holds the value 'bar'.

Now, let's try that out with an array in Bash:
Code:
$ myarr=('foo' 'bar' 'baz')
$ echo ${myarr[*]}
foo bar baz
$ unset myarr[0] # Delete first item
$ echo ${myarr[*]}
bar baz
$ echo ${myarr[0]}
<no output, myarr[0] is gone!>
So, we did not only get rid of the value, but also the index. How do we get around this so that the array in Bash emulates the list in Python?
We reassign the values from the array in which we just deleted the item to a new array, in my case with the same name:
Code:
$ myarr=('foo' 'bar' 'baz')
$ unset myarr[0] # Delete first item
$ myarr=("${myarr[@]}") # Reassign to new array
$ echo ${myarr[*]}
bar baz
$ echo ${myarr[0]}
bar
Now, we have our index 0 back again, containing the value 'bar'!
Posted in Uncategorized
Views 2269 Comments 0
« Prev     Main     Next »
Total Comments 0

Comments

 

  



All times are GMT -5. The time now is 09:40 PM.

Main Menu
Advertisement
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration