如何在shell脚本中检查这个条件?

时间:2018-02-21 04:01:47

标签: linux shell command-line-interface

EG。如果我有一个命令

<package> list --all

命令输出:

Name  ID   
abc    1   
xyz    2 

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

if ($input== $name in command )
   echo "blabla"

2 个答案:

答案 0 :(得分:1)

name=$1
<package> list --all | egrep -q "^$name[ \t]" 
result=$?

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

成功时结果为0,失败时结果为1。

如果名称字面意思是“名称”,它将与标题匹配,如果名称中有空格,则会更复杂。

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

表示“安静”,不要在屏幕上打印匹配的大小写。 $ name包含我们在开头指定的参数。

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

答案 1 :(得分:0)

提供一种替代方法(允许读取和测试多个值而无需重新运行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