0

On the command line you can declare an array as

# a=()

but in inside a script

#!/bin/sh

a=()

echo "length is ${#a[@]}"

it doesn't work.

# sh ./array.sh
./array.sh: 3: Syntax error: "(" unexpected

Is it possible to use arrays in scripts? How?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Richard Barraclough
  • 2,625
  • 3
  • 36
  • 54
  • 2
    So the answer is: _no because `sh` does not have arrays_? – Richard Barraclough Aug 11 '23 at 20:17
  • 1
    Exactly; use Bash or ksh (or Zsh) instead. Your interactive shell is probably Bash or some shell that *does* support arrays. – Benjamin W. Aug 11 '23 at 20:36
  • That is to say, use `./my-script-that-uses-arrays`, and start that script with `#!/bin/bash` or `#!/usr/bin/env bash` (`.sh` [extensions are a bad habit](https://www.talisman.org/~erlkonig/documents/commandname-extensions-considered-harmful/) that encourages people to use `sh` to run even scripts that _aren't_ really POSIX sh scripts, causing the problem seen here; don't perpetuate it). – Charles Duffy Aug 11 '23 at 20:49

0 Answers0