是否有更好的解决此if语句问题?

时间:2019-04-03 09:47:59

标签: bash

Bash函数在找到.git目录的所有子文件夹中执行git pull。

我遇到了最后一个省略号。

此部分:

platform :ios, '12.1'

target 'Questers' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for Questers

pod 'SwiftyJSON'
pod 'TextFieldEffects'
pod 'Alamofire'
pod 'XLPagerTabStrip'
pod 'Eureka' 
pod 'Charts'
pod 'Floaty'
pod 'SVProgressHUD'
pod 'iOSDropDown'
pod 'Firebase/Core'
pod 'Firebase/Auth'
pod 'Firebase/Database'
pod 'Firebase/Messaging'
pod 'MessageKit'
pod 'MessageInputBar'

    target 'QuestersUITests' do
    inherit! :search_paths
    pod 'Firebase'
end

函数的完整代码:

...
elif [ $answer == '' || $answer -ne 'y' || $answer -ne 'n' ] ; then
    echo '---Please answer with y/n---'
...

如果答案为空(按Enter键),不是'y'或不是'n',则应显示文字“请以y或n回答”,并应从“已读答案”重新开始。

有人对此有解决方案吗?

输出:按下Enter键

dogitpull () {
  for i in */.git; do ( echo $i; cd $i/..; ); done
  echo -n 'Are you sure? (y/n) '
  read answer
  echo $answer
  if [ $answer == 'n' ] ; then
    echo '---CANCELED---'
  elif [ $answer == 'y' ] ; then
    echo '---------------------------'
    for d in */.git; do ( echo $d; cd $d/..; git pull; echo '---------------------------'; ); done
  elif [ $answer == '' || $answer -ne 'y' || $answer -ne 'n' ] ; then
    echo '---Please answer with y/n---'
fi
}

输出:输入y或n以外的其他值时

-bash: [: ==: unary operator expected
-bash: [: ==: unary operator expected
-bash: [: missing `]'
-bash: -ne: command not found
-bash: -ne: command not found

3 个答案:

答案 0 :(得分:1)

这里的问题是您没有引用变量。当$answer为空时,[ $answer == '' ]会扩展为[ == '' ],这会产生错误,因为==的左侧没有任何内容。

修复

引用您的变量,然后修复以下错误(由Kamil Cuk提供):

  • -ne是数字,它将以"Integer expression expected"错误。请改用!=
  • ||[无效。使用-o或将||放在括号中:[ ... ] || [ ... ] || [ .. ]

elif [ "$answer" = '' ] || [ "$answer" != 'y' ] || [ "$answer" != 'n' ]

改进

  • 使用单个=而不是==[ a = b]是检查ab是否相等的正式且可移植的方法。
  • 您可能只想写elif [ "$answer" == '' || "$answer" -ne 'y' || "$answer" -ne 'n'而不是else,由于前面的if情况,它具有SAMME效果。

if [ "$answer" = 'n' ] ; then
    # ...
elif [ "$answer" = 'y' ] ; then
    # ...
else
    # ...
fi

答案 1 :(得分:1)

用例。例如:

#!/bin/bash
echo -n 'Are you sure? (y/n) '
read answer
echo $answer
case "$answer" in
        n|N) echo '---CANCELED---';;
        y|Y) echo '-- yes ---';;
        *) echo '---Please answer with y/n---';;
esac

答案 2 :(得分:0)

如果答案不是y 并且不是n,那么您需要采取措施。

elif [ "$answer" != 'y' ] && [ "$answer" != 'n' ]; then
   echo  '---Please answer with y/n---'

或者您可以遵循摩尔定律,并且:

如果不能同时使用:答案为“ Y”或答案为“ n”,则您需要采取措施。

elif ! { [ "$answer" = 'y' ] || [ "$answer" = 'n' ]; }; then
   echo  '---Please answer with y/n---'

或带有(子shell:

elif ! ( [ "$answer" = 'y' ] || [ "$answer" = 'n' ] ); then
   echo  '---Please answer with y/n---'