LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Unable to assign an array in rc.local (https://www.linuxquestions.org/questions/linux-newbie-8/unable-to-assign-an-array-in-rc-local-897567/)

amirgol 08-16-2011 04:34 AM

Unable to assign an array in rc.local
 
I have the following line in my rc.local file:
Code:

USB=( `/usr/bin/file /sys/block/sda | /bin/egrep -o 'usb.*' | /usr/bin/awk -F"/" '{print $1, $2, $3}'` )
It works just fine on any other shell script but in rc.local it stops the execution. I've no idea what happens as this is a headless server, but I know that the internal segment executes just fine: if I place the following line in my rc.local:
Code:

echo `/usr/bin/file /sys/block/sda | /bin/egrep -o 'usb.*' | /usr/bin/awk -F"/" '{print $1, $2, $3}'` >> /root/aaa
I get the expected output (usb1 1-1 1-1.1) in /root/aaa. SO it seems that the array assignment is he culprit here.

Any idea what's happening and how can I solve this? The server is running Debian Wheezy x64.

grail 08-16-2011 05:31 AM

Well I found this with a bit of searching:
Quote:

POSIX and Bourne shells are not guaranteed to have arrays at all.
And then when tested I found the following:
Code:

$ cat test.sh
#!/bin/sh

x=($(/usr/bin/file /sys/block/sda | awk '/^[^0-9]/{c=0}/usb/{c=1}c' RS="/" ORS=" "))

echo "${x[1]}"
$ ./test.sh
./test.sh: 3: Syntax error: "(" unexpected

So I am guessing that this may be happening to you. However, this might help:
Code:

$ cat test.sh
#!/bin/sh

set - $(/usr/bin/file /sys/block/sda | awk '/^[^0-9]/{c=0}/usb/{c=1}c' RS="/" ORS=" ")

echo "$@"
$ ./test.sh
usb9 9-2 9-2:1.0


amirgol 08-16-2011 06:20 AM

Well, my test.sh has no errors ;-). But the same code in rc.local fails. I use the resulting array in a for loop, is there an alternative for it?

grail 08-16-2011 08:15 AM

Quote:

Well, my test.sh has no errors ;-).
When using sh or bash?? It is an important difference as rc normally runs a POSIX shell, generally sh.
Quote:

I use the resulting array in a for loop, is there an alternative for it?
Did you look at my second example??

amirgol 08-16-2011 09:54 AM

Oh, my test file was using bash. Hmm.

Anyway, problem solved: I've learned that a for loop don't need an array, so now everything is working as it should've.

Thanks for the help.


All times are GMT -5. The time now is 02:50 AM.