学习鸟哥Linux shell 时遇到的unexpected operator错误

文章讲述了作者在学习Linuxshellscript时遇到的问题,由于Ubuntu22.4默认使用dash而非bash,导致某些bash语法不被支持。解决方法是用`sudodpkg-reconfiguredash`将系统shell改为bash,确保shellscript正确运行。
摘要由CSDN通过智能技术生成

最近在学习鸟哥Linux,其中一个章节讲解了Linux shell script使用语法,运行总是错误,源码如下:

#!/bin/bash

read -p "Please input (Y/N): " yn

[ "${yn}" == "Y" -o "${yn}" == "y" ] && echo "OK, continue" && exit 0
[ "${yn}" == "N" -o "${yn}" == "n" ] && echo "Oh, interrupt!" && exit 0
echo "I don't know what your choice is" && exit 0

运行报错为:

Please input (Y/N) : n
ans_yn.sh: 5: [: n: unexpected operator
ans_yn.sh: 6: [: n: unexpected operator
I don't know what your choice is

使用的Linux发行版为Ubuntu 22.4,根本原因是:

从Ubuntu 6.10开始,默认使用dash(theDebian Almquist Shell)而不是bash(the GNUBourne-Again Shell).

但Login Shell(一开始通过字符界面登入系统,不是通过x window界面打开terminal终端的shell)还是bash. 原因是dash更快、更高效,而且它符合POSIX规范。Ubuntu在启动的时候会运行很多shell脚本,使用dash可以加快启动速度。

而Bash(GNU Bourne-Again Shell)是大多数Linux平台的内定Shell,也是更经典的shell工具。

在上面的写法中,dash中的语法,两个字符串相等为:

s1 = s2       True if the strings s1 and s2 are identical.
s1 != s2      True if the strings s1 and s2 are not identical.
s1 < s2       True if string s1 comes before s2 based on the ASCII value of their
              characters.
s1 > s2       True if string s1 comes after s2 based on the ASCII value of their
              characters.

因此我们写的shell中使用了“==”判断两个字符串是否相等,故不符

查询一下,sh命令最终指向:

解决办法就是将dash替换为bash

sudo dpkg-reconfigure dash

执行命令会产生一个界面,英文大概意思为:是否使用dash作为默认的系统shell工具,我们选择“No”

执行完,再执行命令:ll  /bin/sh,发现已经替换为bash了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值