A
A
Anatoly2016-05-30 12:17:22
linux
Anatoly, 2016-05-30 12:17:22

How to properly initialize an array in a shell script?

Wrote a small script to search for scripts in a given folder and run them. At startup, it swears at parentheses in the array initialization line.
The script itself:

#!/bin/sh

scripts_path="/home/anatoliy/scripts/test/"
scripts_names=( $(ls -a $scripts_path | egrep '\.sh$') )

for i in "${scripts_names[@]}"; do
  echo "=== Start script $i ==="
  sh $scripts_path$i
  echo "=== End script $i"
done

Error:
test.sh: 4: test.sh: Syntax error: "(" unexpected
OS: Ubuntu 14.04

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anatoly, 2016-05-30
@Anatol_s

I solved the problem not by creating an array in a variable, but by searching for scripts in for.

#!/bin/sh

scripts_path="/home/anatoliy/scripts/test/"

for i in $(ls -a $scripts_path | egrep '\.sh$'); do
  echo "=== Start script $i ==="
  sh $scripts_path$i
  echo "=== End script $i"
done

But why does not want to initialize the array in the previous way, I did not understand.

A
abcd0x00, 2016-05-31
@abcd0x00

Can you try the code

[[email protected] ~]$ arr=($(echo -e "a a\nb b\nc c"))
[[email protected] ~]$ echo ${#arr[@]} ${arr[@]} . ${arr[0]}
6 a a b b c c . a
[[email protected] ~]$

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question