Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays in Shell Script, not Bash

I am probably just having a brain fart, but I can not for the life of me figure out how to loop through an array in shell script, not bash. Im sure the answer is on stackoverflow somewhere already, but I can not find a method of doing so without using bash. For my embedded target system bash is not currently an option. Here is an example of what I am attempting to do and the error that is returned.

#!/bin/sh

enable0=1
enable1=1

port=0
while [ ${port} -lt 2 ]; do
    if [ ${enable${port}} -eq 1 ]
        then
        # do some stuff
    fi

    port=$((port + 1))
done

Whenever I run this script the error "Bad substitution" is returned for line with the if statement. If you guys have any ideas I would greatly appreciate it. Thanks!

like image 642
TheLastFuzzy Avatar asked Sep 29 '14 02:09

TheLastFuzzy


People also ask

Are there arrays in shell script?

There are two types of arrays that we can work with, in shell scripts. The default array that's created is an indexed array. If you specify the index names, it becomes an associative array and the elements can be accessed using the index names instead of numbers.

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

How do you declare an array in a script?

An array can be created using array literal or Array constructor syntax. Array literal syntax: var stringArray = ["one", "two", "three"]; Array constructor syntax: var numericArray = new Array(3); A single array can store values of different data types.


1 Answers

a="abc 123 def"

set -- $a
while [ -n "$1" ]; do
    echo $1
    shift
done

Output via busybox 1.27.2 ash:

abc
123
def
like image 141
mickep76 Avatar answered Oct 15 '22 06:10

mickep76