在OSX上的shell中“读取:-i:invalid option”

时间:2017-06-20 20:02:36

标签: linux bash macos

这个脚本是为linux编写的,我正在尝试将其改编为osx或按原样使用它:

#!/bin/bash
read -e -p "Serial Port                          :" -i "/dev/ttyUSB0" comport
read -e -p "Flash Size (example 512, 1024, 4096) :" -i "4096" fsize
read -e -p "Build (example 71, 72, ..)           :" -i "120" build

size="${fsize}K"
if [ $fsize -gt 1000 ]; then
    size=$(($fsize/1024))"M"
fi

echo "Expected Flash Size: $size"
echo "Using com port: $comport"
if [ -f ESPEasy_R${build}_${fsize}.bin ]; then
    echo "Using bin file: ESPEasy_R${build}_${fsize}.bin [FOUND]"
    ./esptool -vv -cd nodemcu -cb 115200 -bz $size -cp $comport -ca 0x00000 -cf ESPEasy_R${build}_${fsize}.bin
else
    echo "Expected bin file: ESPEasy_R${build}_${fsize}.bin [NOT FOUND!!!]"
fi

我正试图通过进入它的文件夹并编写./flash.sh来运行它,但是我收到了这个错误:

./flash.sh: line 2: read: -i: invalid option
read: usage: read [-ers] [-u fd] [-t timeout] [-p prompt] [-a array] [-n nchars] [-d delim] [name ...]
./flash.sh: line 3: read: -i: invalid option
read: usage: read [-ers] [-u fd] [-t timeout] [-p prompt] [-a array] [-n nchars] [-d delim] [name ...]
./flash.sh: line 4: read: -i: invalid option
read: usage: read [-ers] [-u fd] [-t timeout] [-p prompt] [-a array] [-n nchars] [-d delim] [name ...]
./flash.sh: line 7: [: -gt: unary operator expected
Expected Flash Size: K
Using com port: 
Expected bin file: ESPEasy_R_.bin [NOT FOUND!!!]

我相信我需要以某种方式提供选项,但我无法弄清楚,他们都接缝以获得旗帜我和我也尝试过:

./flash.sh /dev/ttyUSB0 4096 120

1 个答案:

答案 0 :(得分:2)

如错误所述,MacOS上附带的bash版本不支持read -i

你有一些选择:

  • 安装较新的bash版本。 (3.2实际上是十年过时了,因为Apple拒绝受4.0或更新版本的使用限制; MacPorts或Homebrew将使得安装新版本变得容易,并且在脚本中使用#!/usr/bin/env bash作为shebang将确保使用PATH中存在的第一个版本。)
  • 重写您的代码,不需要任何不可用的功能。

作为后者的一个例子:

read -e -p "Serial Port (default: /dev/ttyUSB0)    :" comport; : "${comport:=/dev/ttyUSB0}"
read -e -p "Flash Size (default: 4096)             :" fsize;   : "${fsize:=4096}"
read -e -p "Build (default: 120)                   :" build;   : "${build:=120}"

您还提到了在命令行上传递参数的可能性。坦率地说,允许这样做通常是好习惯,最初编写脚本的人应该已经完成​​了。使用下面的函数来表示命令行值(如果给定),如果没有则提示,并在适当时回退到默认值:

#!/usr/bin/env bash

setvar() {
  local varname argument default prompt
  varname=$1; argument=$2; default=$3; prompt=$4
  if [[ $argument ]]; then
    printf -v "$varname" %s "$argument"
  elif read -r -e -p "$prompt" "$varname" && [[ $varname ]]; then
    return 0
  else
    printf -v "$varname" %s "$default"
  fi
}

setvar comport "$1" "Serial Port (default: /dev/ttyUSB0)    :" /dev/ttyUSB0
setvar fsize   "$2" "Flash Size (default: 4096)             :" 4096
setvar build   "$3" "Build (default: 120)                   :" 120

# ...etc here.