LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Bash array to function (https://www.linuxquestions.org/questions/programming-9/bash-array-to-function-602778/)

rejeep 11-27-2007 12:40 PM

Bash array to function
 
Hi!

How can I manipulate an array in BASH?

For example. After the call of function a I want the first element in the array to have been removed. So the output after the call should be b c.
Code:

#!/bin/bash

function a()
{
    unset $1[0]
}

array=( "a" "b" "c" )
echo "${array[@]}" // Output is "a b c"
a "${array[@]}"
echo "${array[@]}" // Output is "a b c", but should be "b c"

Thanks!

slakmagik 11-27-2007 12:55 PM

What exactly are you trying to do? $1 is not an array variable. You would delete an array index with 'unset array[0]'. And then the function doesn't get you much, as it's a one token reference to a one token command.

rejeep 11-27-2007 12:59 PM

Quote:

Originally Posted by digiot (Post 2972397)
What exactly are you trying to do?

I'm trying to manipulate an array in a function where the array was given as an argument to the function.

In the example above I'm trying to remove the first element from the array named array.

radoulov 11-27-2007 01:40 PM

Quote:

Originally Posted by rejeep (Post 2972402)
I'm trying to manipulate an array in a function where the array was given as an argument to the function.

In the example above I'm trying to remove the first element from the array named array.

Code:

bash 3.2.25(1)$ array=( "a" "b" "c" )
bash 3.2.25(1)$ echo "${array[@]}"
a b c
bash 3.2.25(1)$ a(){ unset "$1"[0];}
bash 3.2.25(1)$ a array
bash 3.2.25(1)$ echo "${array[@]}"
b c


rejeep 11-27-2007 01:45 PM

Thanks! =)

radoulov 11-27-2007 02:05 PM

Quote:

Originally Posted by rejeep (Post 2972443)
Thanks! =)

Consider that after removing the first element,
the next time you run a array nothing will happen
(you'll have no more ${array[0]} element.


All times are GMT -5. The time now is 12:30 AM.