在插入 #!/bin/sh 时出现未找到的错误

3

我开始学习Linux shell脚本编程。当我编写这个脚本时,出现了错误。

./my_script: 4: read: Illegal option -n
./my_script: 5: ./my_script: [[: not found

我发现问题出在#!/bin/sh这一行,如果我不加这一行也可以运行脚本,但是像/n这样的代码就不会被执行。

#!/bin/sh
# Shell installer for gurb customizer. by Naveen Gamage.

OS=$(lsb_release -si)
ARCH=$(uname -m | sed 's/x86_//;s/i[3-6]86/32/')
VER=$(lsb_release -sr)

grabninstall() {
    sudo add-apt-repository ppa:danielrichter2007/grub-customizer
    sudo apt-get update
    sudo apt-get install grub-customizer    
}

echo "Installer for GRUB CUSTOMIZER\n"
echo "GURB CUSTOMIZER"
echo "A tool for editing and configuring boot menu (GRUB2/BURG).\n"

read -p "Do you want to install Grub Customizer for $OS ${VER} [$ARCH] ? (Y/n) " -n 1

if [[ $REPLY =~ ^[Yy]$ ]]
then
    echo "The installer is downloading and installing GRUB Customizer!";
    echo "This action may require your password.\n";
    grabninstall
else
    echo "user quit"
    echo "Installation was unsuccessful."
fi

我正在使用Ubuntu 12.10。

which sh的输出结果为:

/bin/sh

我做错了什么?


1
ls -l /bin/sh 是否指向 bash - dogbane
是的,lrwxrwxrwx 1 root root 4 May 13 16:01 /bin/sh -> dash - Michael Gamage
1个回答

7
问题在于您使用了/bin/sh来运行脚本,在您的系统上,/bin/sh -> dash。这意味着dash正在执行您的脚本。dash shell不支持[[,但是bash支持。因此,您应该将脚本中的第一行(称为Shebang)从#!/bin/sh更改为#!/bin/bash

或者,不要在脚本中使用[[。仅使用dash支持的功能。

另请参阅Ubuntu页面,了解dash不支持哪些结构。


为什么Bash不支持\n命令?即用于输出空行的命令。 - Michael Gamage
除了echo ""之外,还有其他方法可以输出空行吗? - Michael Gamage
使用 echo -e 命令打印空行。例如:echo -e "hello\nworld" - dogbane
1
使用 echo 命令打印空行(无参数)。如果需要考虑可移植性,请勿使用带参数的 echo 命令(例如 echo -n/echo -e),而应改用 printf 命令(链接)。 - Adrian Frühwirth

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