Check String in List Bash
To determine if a string is in a list in a shell script, you can use a loop to iterate through the list and check for the string.
Here is an example code:
#!/bin/bash
# 列表
list=("apple" "banana" "orange" "grape")
# 需要判断的字符串
str="orange"
# 判断字符串是否在列表中
found=false
for item in "${list[@]}"; do
if [ "$item" == "$str" ]; then
found=true
break
fi
done
# 输出结果
if [ "$found" == true ]; then
echo "字符串 '$str' 在列表中"
else
echo "字符串 '$str' 不在列表中"
fi
In the above sample code, a list is first defined, followed by a string that needs to be checked. Next, a for loop is used to iterate through the list, comparing each element with the string to determine if a matching string is found. If a match is found, the “found” variable is set to true and the loop is exited. Finally, the result is output based on the value of the “found” variable.
Running the above code will output the string ‘orange’ is in the list. If the str variable is changed to a string that is not in the list, the output will be the string ‘xxx’ is not in the list.