-1

I would like to do something that is very simple (and with a lot of tutorials) in other languages like python or C, but in bash script.

I would like to work with lists (of strings but could be for anything I suppose) In concrete I want to

  • Create an empty list
  • Add an element to the list
  • Check if the list is empty
  • Erase an element of the list
  • Refer to an element of the list by index (to go to "the next")

How can I implement this in bash script? (If lists are not available, perhaps then arrays?)

KansaiRobot
  • 7,564
  • 11
  • 71
  • 150
  • Bash just has arrays, which can be either indexed or associative. They can just contain strings, there are no higher level structures in bash. – Barmar Aug 29 '21 at 06:34
  • 1
    Read about them in the [bash manual](http://www.gnu.org/software/bash/manual/html_node/Arrays.html#Arrays) – Barmar Aug 29 '21 at 06:35
  • I have managed to resolve almost all of what I asked. The only thing I still don't know is how to remove an element of the array – KansaiRobot Aug 29 '21 at 07:13
  • https://stackoverflow.com/questions/16860877/remove-an-element-from-a-bash-array – Barmar Aug 29 '21 at 07:17
  • `unset` is how to do that. – Shawn Aug 29 '21 at 07:22
  • You could use a **Redis** list then your array would be accessible across your entire network, e.g. `redis-cli lpush array value` stores a value in a list and `redis-cli lset array 3 "hello"` changes entry 3 to "hello". – Mark Setchell Aug 29 '21 at 08:11

1 Answers1

0

Before my question is closed ... I put here some answers

-Create an empty list

arr=()

-Add an element to the list

~~Not sure about this. I thought it was arr=($newvalue "$arr[@]") but it is not.~~

arr=( $newvalue "${arr[@]}")
  • Check if the list is empty
if ((${#arr[@]})); then   #the number is not 0
  echo "array is not empty"
else
  echo  "array is empty"
fi
  • Erase an element of the list OPEN QUESTION

  • Refer to an element of the list by index (to go to "the next")

echo ${arr[0]}

I think it is very important to put all these in a question and not going all around the internet to find the answers so here it goes

#create an empty array
arr=()
#arr=("eee")
echo "empty array"
echo ${arr[@]}
newvalue=000

#add new element
echo "add elements"

arr=("new_element" "${arr[@]}")
echo ${arr[@]}

arr=( $newvalue "${arr[@]}")
echo ${arr[@]}

echo "first element and number of elements"
echo ${arr[0]}   #refer to an element by index 
echo ${#arr[@]}  #number

echo "is it empty"
if ((${#arr[@]})); then   #the number is not 0
  echo "array is not empty"
else
  echo  "array is empty"
fi

echo "delete element"
arr=("${arr[@]/$newvalue}" )
echo ${arr[@]}
KansaiRobot
  • 7,564
  • 11
  • 71
  • 150