0

I have this bash script that starts with

for d in /data/mydata/*; do
    echo $d
    filepath=$(echo $d | tr "/" "\n")
    pathArr=($filepath)       # fails here
    echo ${pathArr[-1]}

It runs fine when I just call in on command line

./run_preprocess.sh

but when I run it using screen

screen -dmSL run_preproc ./run_preprocess.sh

it fails on that pathArr line

./run_preproc.sh: 7: ./run_preproc.sh: Syntax error: "(" unexpected (expecting "done")

is there something I need to do to protect the script code?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
bhomass
  • 3,414
  • 8
  • 45
  • 75

1 Answers1

1

Based on the error, looks like you're running your script with POSIX sh, not bash. Arrays are undefined in POSIX sh.

To fix this, add a proper hashbang to your script (e.g. /usr/bin/env bash, or run the script directly with Bash interpreter (e.g. /bin/bash script.sh).


In addition (unrelated to the problem at hand), your script (or the snippet posted) has several potential issues:

  • variables should be quoted to prevent globbing and word splitting (e.g. consider d - one of your files - containing * -- echo $d will include a list of all files, since * will be expanded)

  • splitting into array with ($var) is done on any IFS character, not just newlines. IFS includes a space, tab and newline by default. Use of read -a or mapfile is recommended over ($var).

Finally, if all you're trying is get the last component in path (filename), you should consider using basename(1):

$ basename /path/to/file
file

or substring removal syntax of Bash parameter expansion:

$ path=/path/to/file
$ echo "${path##*/}"
file
randomir
  • 17,989
  • 1
  • 40
  • 55