2

I have created an array (3 elements), and each element contains a comma delimited string. The array was created by reading a file line by line - the file contains fields output from a database. I have written the code below in order to iterate through each string element, as though it were too an array.

It works, apart from one strange error, the last element in the array has an additional @ symbol

(also declare -A didn't work, though I've made sure I'm using bash 4 on my mac)

i=0
declare -a items
while read line
    do
        items[i]=$line
    ((i++))
    done < test_file1.txt

declare -a item_arr
for item in "${items[@]}"
   do
     item_arr=($item[@])
   done
echo "${item_arr[4]}://${item_arr[1]}:${item_arr[3]}@${item_arr[2]}/control/configinfo"

output is: https[@]://192.168.1.152:username@pwd/control/configinfo

Why is the @ symbol printing out? Am I wasting my time, should i have used awk instead? otherwise, it feels like a fairly straightforward way, but that could be as I'm relatively inexperienced. Potentially the most items I may need to initialise in this would be 1 to 200.

The purpose of my code is to create a curl request to obtain some config_info, the user name, password, ip address, protocol are all pulled from a database in order to build a curl request for each item.

thanks in advance!

3 Answers 3

2

item is a scalar string variable (not an array), so you should say

item_arr=($item)

rather than

item_arr=($item[@])

If $item is The quick brown fox, then

item_arr=($item[@])

becomes

item_arr=(The quick brown fox[@])
1
  • Amazing! Thanks so much! I can see why I got confused and didn't realise
    – jewfro
    Mar 17, 2015 at 7:39
1

You're right that awk would be easier.

Source example /tmp/test2.txt:

$ cat /tmp/test2.txt
192.168.1.152 pwd username https
$ awk '{print $4 "://" $1 ":" $3 "@" $2 "/control/configinfo" }' /tmp/test2.txt
https://192.168.1.152:username@pwd/control/configinfo
1

If you want a simpler way to do this in pure bash, assuming that you don't need to keep the file contents (IP addresses, user names, passwords, etc.) in shell memory (i.e., in an array), you can do this:

while read ip_address pwd username protocol
do
        echo "${protocol}://${ip_address}:$username@$pwd/control/configinfo"
done < test_file1.txt

This may be easier to maintain than the awk solution.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .