1

I have the following script written in linux bash to check if file exists and I can read its contents. When run manually its working. But when I run the script, return code is blank.

${PARAM_FILES_ARR[@]} has values like /somedir/file1.prm, /somedir/files2.prm etc.

Edit: As per comments I am adding assignment of ${PARAM_FILES_ARR[@]} as follows.

cdoe written below. Plesae help.

#!/bin/bash
...some code...
#The array gets assigned as below from a file in the same script
PARAM_FILES_ARR=($(cat $PARAM_FILES_LIST | sed '/^[[:blank:]]*$/d' | sed '/^[#]/d' | sed '/^[$]{2}/d' | sed 's/^[[:blank:]]*//' | sed 's/[[:blank:]]*$//' | sed 's/\\/\//g' | envsubst))

for FNAME in "${PARAM_FILES_ARR[@]}"
    do
        cat "${FNAME}" > /dev/null 2>&1
        RETURN_CODE_FILE=$?
        if [ "${RETURN_CODE_FILE}" -ne 0 ]; then
            echo "Warning! Could not Read PARAM FILE ${FNAME}"
            echo "${RETURN_CODE_FILE}"
        fi
    done
  • 4
    Do you set PARAM_FILES_ARR externally? Why don't you use a regular test `[ -r "$FNAME" ]`? – Allan Wind Jan 23 '23 at 07:33
  • I don't see that you would actually set `PARAM_FILES_ARR`. If you don't set it, it would have to be an environment variable, **but** you use the variable as an array, and environment variables are not arrays, but simple strings. Also, I don't understand the purpose of the `cat` command. – user1934428 Jan 23 '23 at 10:08
  • @user1934428 Sorry forgot to add it question. Just Edited the question.. – Srinivasarao Kotipatruni Jan 23 '23 at 16:15

2 Answers2

4

Simplify

for fname; do
    if [[ -r $fname ]]; then
        echo "$fname readable"
    else
        echo "$fname unreadable"
    fi
done

Usage

./script <*files> or <bash array>

To go deeper

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
-1

Your script don't see an array with files as Allan Wind suggested in comments. Try to change it like so:

#!/bin/bash
for FNAME in "$@"
    do
    ...

And run like this:

./script_name "${PARAM_FILES_ARR[@]}"
Ivan
  • 6,188
  • 1
  • 16
  • 23
  • No need `$@`, check my answer ;) – Gilles Quénot Jan 23 '23 at 08:14
  • @GillesQuenot I've checked your answer 5 edits back ;) You're right `$@` could be omitted, but I left it to make answer more similar to OP's style. And it's more readable this way(IMHO). – Ivan Jan 23 '23 at 09:39