Linux脚本,提示/读取+字符串相等运算符+正则表达式

时间:2014-05-19 22:53:35

标签: linux

这是一个简单的问题,我整个周末都在苦苦挣扎。我想提示用户键入[TtMm],如果他/她没有,则再次提示。翻译发现了一些我不理解的语法错误。

谢谢,

#!/bin/bash

use_selection=H
while [ $use_selection != [TtMm]  #interpreter says this is missing a `
do
echo "Get Target (T/t) or name (M/m)"
read use_selection
echo $use_selection
done

2 个答案:

答案 0 :(得分:2)

portable shell中执行此操作的最佳方法是

#! /bin/sh

while :; do 
    echo "Get Target (T/t) or name (M/m)?"
    read use_selection
    case "$use_selection" in
        [TtMm]) break;;
             *) echo "Invalid selection" >&2;;
    esac
done
echo "$use_selection"

它也可以用expr来完成,但是它具有更多的可移植性。

不要编写不可移植的shell脚本;特别是,永远不要使用Bash扩展。如果您处于延伸似乎是阻力最小的路径的情况下,如果您停止并以更好的语言重写整个脚本,您几乎肯定会更开心。 Perl或Python。

答案 1 :(得分:1)

#!/bin/bash

use_selection=H
while [[ ! "$use_selection" == [TtMm] ]] 
do
echo "Get Target (T/t) or name (M/m)"
read use_selection
echo $use_selection
done