Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In array operator in bash

Tags:

arrays

bash

shell

Is there a way to test whether an array contains a specified element?

e.g., something like:

array=(one two three)

if [ "one" in ${array} ]; then
...
fi
like image 867
ʞɔıu Avatar asked May 02 '11 00:05

ʞɔıu


People also ask

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script.

What are [] in bash?

[[ … ]] double brackets are an alternate form of conditional expressions in ksh/bash/zsh with a few additional features, for example you can write [[ -L $file && -f $file ]] to test if a file is a symbolic link to a regular file whereas single brackets require [ -L "$file" ] && [ -f "$file" ] .

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc.

Is there an array in bash?

Bash provides one-dimensional indexed and associative array variables. Any variable may be used as an indexed array; the declare builtin will explicitly declare an array. There is no maximum limit on the size of an array, nor any requirement that members be indexed or assigned contiguously.


1 Answers

A for loop will do the trick.

array=(one two three)

for i in "${array[@]}"; do
  if [[ "$i" = "one" ]]; then
    ...
    break
  fi
done
like image 78
Frank Avatar answered Nov 05 '22 01:11

Frank