[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Passing elements to function

From: Pierre Gaston
Subject: Re: [Help-bash] Passing elements to function
Date: Sun, 15 Oct 2017 08:30:11 +0300

On Sun, Oct 15, 2017 at 12:13 AM, Jerry <address@hidden> wrote:

> I am new to programing in bash. I am trying to copy data from an array to a
> file. I got this script snippet while Googling.
> for j in "address@hidden"
> do

expands to the number of elements, so it will be only one number, this loop
is useless here

a much better way wood be to directly loop on the elements of the array
for elem in  "address@hidden";do
  echo "${elem}" >> "${file}"

or slightly more efficient
for elem in  "address@hidden";do
  echo "${elem}"
done >> "${file}"

since echo can cause trouble (eg if elem=-n) it's better to use printf, in
fact printf can print multiple arguments
so you can just do:
printf '%s\n' "address@hidden" >> "${file}"

> Now, I want to make this into a function, so I wrote it as this:
> array2file () {
> for j in "$1"
> do
> index=0
> element_count="${j}"
> while [ "${index}" -lt "${element_count}" ]
> do    # List all the elements in the array.
> echo "${$3[${index}]}" >> $2

The problem is here, this just doesn't work, the keyword you would need
would be "indirection"
or name reference.

Before that though, a simpler solution is to pass the elements something

array2file () {
local file elem
file =$1
for elem in "$@";doe
  echo "$elem"
done >> "$file"

array2file  "filename.txt"  "address@hidden"

with indirections it could be something like:

array2file () {
  declare -n array2file_array="$2"
  printf "%s\n" "address@hidden" >> "$1"

array2file filename.txt array

reply via email to

[Prev in Thread] Current Thread [Next in Thread]