繁体   English   中英

如何在shell脚本中检查这种情况?

[英]How do I check this condition in shell script?

例如。 如果我有命令

<package> list --all

命令输出:

Name  ID   
abc    1   
xyz    2 

如何使用Shell脚本检查用户输入的名称是否与列表中的名称相同。 像这样:

if ($input== $name in command )
   echo "blabla"
name=$1
<package> list --all | egrep -q "^$name[ \t]" 
result=$?

package的某种可疑符号来自于问题,是一种占位符。

结果将为0(成功)和1(失败)。

如果名称从字面上是“名称”,则它将与标题匹配,并且如果名称中可能包含空格,则将更加复杂。

egrep -q "^$name[ \t]"

表示“安静”,请勿在屏幕上打印匹配的大小写。 $ name保存参数,该参数是我们开头分配的。

“ ^”阻止“ bc”匹配-表示“行开始”。 “ [\\ t]”捕获空格和制表符作为单词标记的结尾。

提供另一种方法(允许读取和测试多个值而无需重新运行list命令或进行O(n)查找):

#!/usr/bin/env bash

case $BASH_VERSION in
  '')       echo "This script requires bash 4.x (run with non-bash shell)" >&2; exit 1;;
  [0-3].*)  echo "This script requires bash 4.x (run with $BASH_VERSION)" >&2; exit 1;;
esac

declare -A seen=( )                 # create an empty associative array
{
  read -r _                         # skip the header
  while read -r name value; do      # loop over other lines
    seen[$name]=$value              # ...populating the array from them
  done
} < <(your_program list --all)      # ...with input for the loop from your program

# after you've done that work, further checks will be very efficient:
while :; do
  printf %s "Enter the name you wish to check, or enter to stop: " >&2
  read -r name_in                      # read a name to check from the user
  [[ $name_in ]] || break              # exit the loop if given an empty value
  if [[ ${seen[$name_in]} ]]; then     # lookup the name in our associative array
    printf 'The name %q exists with value %q\n' "$name_in" "${seen[$name_in]}"
  else
    printf 'The name %q does not exist\n' "$name_in"
  fi
done

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM