Bash读取输入 - 制表符提示

5
我有一个脚本,用于读取用户输入。以下是我的代码:

if [ -z $volreadexists ]; then
        echo -e "\tThis will overwrite the entire volume (/dev/vg01/$myhost)...are you sure?"
        read REPLY
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            echo -e "\t\tContinuing"
            syncvolume
        else
            echo "Fine...skipping"
        fi
    fi

我不得不使用read REPLY,因为单独使用read无法插入制表符。我正在寻找类似于:

read -p "\tDoes this look OK? (n for No)" -n 1 -r

在读取提示符上方按下\t可以进行缩进。

如何在读取提示符中添加制表符?

更新:感谢@gniourf提供的出色答案!

read -p $'\tDoes this look OK? (n for No)' -n 1 -r

然而,我发现了一个问题。当我尝试在那里使用变量时,它不会将其翻译:
read -p $'\tThis will overwrite the entire volume (/dev/vg01/$myhost)...are you sure? ' -n 1 -r

变成

        This will overwrite the entire volume (/dev/vg01/$myhost)...are you sure?

where I want:

        This will overwrite the entire volume (/dev/vg01/server1)...are you sure?

使用双引号也不起作用 :(

有什么想法吗?


2
只需使用ANSI-C引用read -p $'\t这看起来可以吗?(n表示否)' -n 1 -r - gniourf_gniourf
1
看起来不错!很棒,谢谢! - user3063045
1
@gniourf_gniourf,你应该将它添加为答案,这样它就可以被投票和(更重要的是)接受了。 - Anthony Geoghegan
1
是的,添加一个回答 - 获得积分 :) - user3063045
1
这是因为$“…”完全做了另一件事。但你不必局限于单引号或双引号。 - Ignacio Vazquez-Abrams
2个回答

4

只需使用ANSI-C引用即可:

read -p $'\tDoes this look OK? (n for No)' -n 1 -r

现在,如果您也想使用变量扩展,可以像这样混合使用不同的引号:
read -p $'\t'"This will overwrite the entire volume (/dev/vg01/$myhost)...are you sure? " -n 1 -r

在这里,我只使用了 ANSI-C 引用来表示制表符。确保在 $'\t'"This will...." 之间不要留任何空格。


0
我最终参考了这个答案:

在bash中读取带有默认值的变量

然后创建了一个解决办法。虽然不完美,但是有效:

myhost="server1"
if [ -z $volreadexists ]; then
    read -e -i "$myhost" -p $'\tJust checking if it\'s OK to overwrite volume at /dev/vg01/'
    echo
    if [[ $REPLY =~ ^$myhost[Yy]$ ]]; then
        echo -e "\t\tContinuing"
    else
        echo "Fine...skipping"
    fi
fi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接