Bash- if子句无法正常工作 [英] Bash- if clause doesn't work correctly

查看:85
本文介绍了Bash- if子句无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个关闭脚本,它无法按预期工作.这就是我写的.

I want to make a shutdown script and it doesn't work as intended. This is what I wrote.

echo "Wanna shutdown (y/n)?"

 read ANSWER

if [ $ANSWER=="y" ]
     then
        sudo shutdown -P now
else 
    printf "Something...."

无论我按什么按钮,它都会关闭.为什么?

whatever i press it just shuts down. Why?

推荐答案

您需要在==运算符周围放置空格.否则,测试表达式只能是一个单词,并且所有非空单词都可以成功测试.

You need to put spaces around the == operator. Otherwise the test expression is a single word, and all non-empty words test successfully.

此外,如果希望便携,则应使用=而不是==.并且总是用双引号括起变量扩展是明智的,因为[不会为您这样做.

In addition, if you wish to be portable, you should use = instead of ==. And it is always wise to double quote variable expansions because [ won't do that for you.

if [ "$ANSWER" = y ]; then

另一方面,如果您使用的是bash(或ksh或zsh),则可以使用更宽容的[[条件表达式:

On the other hand, if you are using bash (or ksh or zsh) you could use the more forgiving [[ conditional expression:

if [[ $ANSWER = y ]]; then

这篇关于Bash- if子句无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆