简体   繁体   English

Bash脚本“找不到fi行”

[英]Bash script “fi lines not found”

This is my first bash script ever, essentially it just shuts off my second monitor. 这是我有史以来第一个bash脚本,本质上它只是关闭了我的第二个监视器。 But I've been having problems with it, as it keeps giving me errors when I run it. 但是我一直在遇到问题,因为它在运行时总是给我错误。

#!/bin/bash


read -p "Do you want the 2nd monitor on or off? " ON_OFF

if [$ON_OFF == on]; then
xrandr --output DVI-I-3 --auto --right-of DVI-I-0
echo "done"
fi

if [$ON_OFF == off]; then
xrandr --output DVI-I-3 --off   
echo "done"
fi

When I run it I get 当我运行它时,我得到

monitor_control.sh: 11: [[off: not found
monitor_control.sh: 16: [[off: not found

Can anybody explain to me why it's not working? 有人可以向我解释为什么它不起作用吗?

You need to add space around [ and ] , as they are separate commands in bash. 您需要在[]周围添加空格,因为它们是bash中的单独命令。

Moreover, either quotes need to be used around parameter expansions, or [[ ]] needs to be used instead of [ ] . 此外,要么需要在参数扩展名前后使用引号,要么需要使用[[ ]]代替[ ]

That is, you can either use: 也就是说,您可以使用:

if [[ $ON_OFF = on ]]

...or you can use: ...或者您可以使用:

if [ "$ON_OFF" = on ]

Otherwise you will get error if $ON_OFF is empty. 否则,如果$ON_OFF为空,则会出现错误。

Finally, it's better to use if ... then ... else ... fi , like: 最后,最好使用if ... then ... else ... fi ,例如:

if [[ $ON_OFF = on ]]; then
    xrandr --output DVI-I-3 --auto --right-of DVI-I-0
else
    xrandr --output DVI-I-3 --off   
fi
echo "done."

This should work. 这应该工作。

#!/bin/bash


echo -n "Do you want the 2nd monitor on or off? "
read ON_OFF;

if [ $ON_OFF == "on" ]; then
  xrandr --output DVI-I-3 --auto --right-of DVI-I-0
  echo "done"
fi

if [ $ON_OFF == "off" ]; then
  xrandr --output DVI-I-3 --off
  echo "done"
fi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM