使用sh解释器运行时读取用户输入未运行的脚本

时间:2019-03-01 06:19:12

标签: bash shell

这可能是bash user input if的重复,但是答案不能解决我的问题,所以我认为还有其他问题。

我有下一个脚本:

#!/bin/bash

echo "Do that? [Y,n]"
read input
if [[ $input == "Y" || $input == "y" ]]; then
        echo "do that"
else
        echo "don't do that"
fi

当我做sh basic-if.sh

enter image description here

我也有

#!/bin/bash

read -n1 -p "Do that? [y,n]" doit 
case $doit in  
  y|Y) echo yes ;; 
  n|N) echo no ;; 
  *) echo dont know ;; 
esac

当我做sh basic-if2.sh

enter image description here

我认为我的bash有问题,因为其他用户在运行这些示例时并没有遇到这些问题。谢谢

1 个答案:

答案 0 :(得分:2)

使用sh scriptname运行脚本会覆盖脚本中设置的所有默认解释器。在您的情况下,bourne shell(sh)运行脚本,而不是bourne again shell(bash)。 sh不支持[[,并且符合POSIX格式的read命令不支持-n标志。

很可能您的系统中的sh没有与bash链接,并且它本身是作为POSIX兼容外壳程序运行的。通过运行来解决问题

bash basic-if2.sh

或在脚本名称之前使用./来运行它,方法是使系统在文件(#!/bin/bash)的第一行中寻找解释器。除了修复解释器外,您还可以为操作系统执行#!/usr/bin/env bash,以查找bash的安装位置并执行该操作。

chmod a+x basic-if2.sh
./basic-if2.sh

您还可以查看是否ls -lrth /bin/sh链接到dash,这是Debian系统上可用的最小POSIX兼容外壳。