commoccoom
V2EX  ›  问与答

鸟哥 Linux 私房菜里的一个 shellscript 例题。但是执行的时候发生错误,求指导。

  •  
  •   commoccoom · Dec 8, 2014 · 3671 views
    This topic created in 4365 days ago, the information mentioned may be changed or developed.
    1 #!/bin/bash
    2 #Porgram
    3 # This program shows the user's choice.
    4 #History
    5 #2014/12/08
    6 PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
    7 export PATH
    8
    9 read -p "Please input (Y/n):" yn
    10 [ "$yn" == "Y" -o "$yn" == "y" ] && echo "OK.continue" && exit 0
    11 [ "$yn" == "N" -o "$yn" == "n" ] && echo "Oh,interrupt!" && exit 0
    12 echo "I don't know what your choice is" && exit 0
    13


    完全按照书上写的,但是运行错误。

    root@default:~/shell# sh sh06.sh
    Please input (Y/n):y
    sh06.sh: 10: [: y: unexpected operator
    sh06.sh: 11: [: y: unexpected operator
    I don't know what your choice is
    root@default:~/shell#
    Supplement 1  ·  Dec 8, 2014
    已经解决!感谢所有人员!
    12 replies  •  2014-12-08 22:52:44 +08:00
    adjusted
    adjusted
    Dec 8, 2014❤️1
    1
    你确定你都输入对了?看不出什么问题啊。。。
    kidlj
    kidlj
    Dec 8, 2014❤️2
    2
    是这样的,因为你执行这个脚本用的 `/bin/sh`,而不是 `/bin/bash`,sh 是不支持 `==` 这个比较操作符的,它用 `=` 代表等于。你没看错,这就是POSIX标准。

    而bash是支持`==`操作的。所以你可以:

    - 用 bash 来执行这个脚本

    - 如果非要用 sh 来执行,那么就把`==` 改成 `=`


    另外不要用`root`来实验和执行脚本呢?这样是很危险的。
    ZircoN
    ZircoN
    Dec 8, 2014❤️1
    3
    直接 ./sh06.sh 试试 楼上貌似正解。
    adjusted
    adjusted
    Dec 8, 2014❤️1
    4
    怎么记得sh是link到bash的...
    caixiexin
    caixiexin
    Dec 8, 2014❤️1
    5
    我发现好像是空格问题你的脚本==左右两边是不是有空格?我把你的拷贝下来,去掉==两边的空格是能运行的
    commoccoom
    commoccoom
    OP
    Dec 8, 2014
    6
    @kidlj
    感谢!

    因为是个用来扶墙的微型VPS,只装了SS,所以就用root了 ,挂了就重装~。~
    bitwing
    bitwing
    Dec 8, 2014❤️1
    7
    @adjusted Debian 系的某些是链接到 dash 的......
    nealfeng
    nealfeng
    Dec 8, 2014❤️1
    8
    @commoccoom 本地虚拟机就好了,何必上vps折腾学linux
    commoccoom
    commoccoom
    OP
    Dec 8, 2014
    9
    @caixiexin
    去掉空格后确实行了。另外2楼的方法也是行的。

    但是鸟哥在书上还强调要加空格~。~
    commoccoom
    commoccoom
    OP
    Dec 8, 2014
    10
    @nealfeng
    手机端装个SSH客户端能登录VPS,利用点碎时间看看脚本什么的~。~
    caixiexin
    caixiexin
    Dec 8, 2014
    11
    @commoccoom 要看你看的书是第几版了,之前买的时候就看书评有人说新版排版有问题,有几个示例脚本会多空格导致脚本执行错误,所以就拿你发的试了一下,没想到你果然被书坑了2333
    Muninn
    Muninn
    Dec 8, 2014
    12
    主要要看sh被链接到啥了...
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2050 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 07:06 · PVG 15:06 · LAX 23:06 · JFK 02:06
    ♥ Do have faith in what you're doing.