Bash scripting: how to check list membership

(This is debian squeeze amd64)

I need to check if the file is a member of the file list. So far, my (test) script:

set -x
array=$( ls )
echo $array
FILE=log.out
# This line gives error!
if $FILE in $array
then   echo "success!"
else  echo "bad!"
fi
exit 0

¿Any ideas?

Thanks for all the answers. To clarify: the script below is just an example, the actual problem is more complicated. In the final solution, this will be done in a loop, so I need the file (name) to be checked in order to be in a variable.

Thanks again. There is no my test - the script works and reads:

  in_list() {
       local search="$1"
       shift
       local list=("$@")
       for file in "${list[@]}" ; do
           [[ "$file" == "$search" ]] && return 0
       done
       return 1
    }
    #
    # set -x
    array=( * )  # Array of files in current dir
    # echo $array
    FILE="log.out"
    if in_list "$FILE" "${array[@]}" 
    then   echo "success!"
    else  echo "bad!"
    fi
    exit 0
+3
source share
3 answers
if ls | grep -q -x t1 ; then
  echo Success
else
  echo Failure                                                                                
fi

grep -xmatches only complete lines, so ls | grep -xreturns only something if the file exists.

+3
source

What about

in_list() {
    local search="$1"
    shift
    local list=("$@")
    for file in "${list[@]}" ; do
        [[ $file == $search ]] && return 0
    done
    return 1
}

if in_list log.out * ; then
    echo 'success!'
else
    echo 'bad!'
fi

EDIT: made him a little less idiotic.

№ 2: , , , , , - , , ,

[ -e log.out ] && echo 'success!' || echo 'bad!'

- , .

+2

If you just want to check if a file exists, then

[[ -f "$file" ]] && echo yes || echo no

If your array contains a list of files generated in some other way than that ls, you will have to iterate over it, as shown by Sorpigal.

+2
source

Source: https://habr.com/ru/post/1777744/


All Articles