coverl 发表于 2018-8-29 13:30:16

unexpected operator--shell script

  我在ubuntu虚拟机下练习《鸟哥的Linux私房菜》中的shell脚本例子时,我习惯用vim编写完直接用sh xxx.sh来运行,
  并且还可以用sh -n xxx.sh 或者-x,-v等参数来调试脚本。当运行if then语句的例子时,突然报错:xxx unexpected operator,
  我暂且没有管它,因为我认为代码没有问题,并且我把if then的语句理解了就达到了学习的目的。
  但是在练习用“[ ]”中括号来做判断时,还是这个问题,我决定寻求网络解决这个问题。
  代码类似:
   view plaincopyhttps://code.csdn.net/assets/CODE_ico.pnghttps://code.csdn.net/assets/ico_fork.svg

[*]  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
   view plaincopyhttps://code.csdn.net/assets/CODE_ico.pnghttps://code.csdn.net/assets/ico_fork.svg

[*]  #!/bin/bash
[*]
[*]  read -p "input yes or no(Y/N):" yesorno
[*]
[*]  if [ "$yesorno" == "Y" ] || [ "$yesorno" == "y" ]; then
[*]  echo "okay, you say yes."
[*]  else
[*]  echo "oh, no."
[*]  fi
  原因应该是在ubuntu中默认的脚本语言是dash,用sh运行会采用dash的语言规则,所以会有如此错误。
  如果用“./xxx.sh”来运行就没有问题了。那么咱们必须要用sh加参数来调试我们的脚本,怎么办?
  好办,只需做一下配置修改就可以了。将使用dash 作为默认的系统脚本的选项取消掉。
  命令为:
   view plaincopyhttps://code.csdn.net/assets/CODE_ico.pnghttps://code.csdn.net/assets/ico_fork.svg

[*]  sudo dpkg-reconfigure dash
  此时会跳到下面的配置页面,选择no并回车就好了。http://img.blog.csdn.net/20140914104228059

页: [1]
查看完整版本: unexpected operator--shell script