基本的bash脚本问题

时间:2017-06-07 15:46:19

标签: bash

这是我在论坛上的第一篇文章,让我知道我是否可能更具描述性。 昨天,我写了一篇文章。脚本启动,重新启动和停止我的服务器,所以我测试$ 1参数3次,以了解它是否启动,重启,停止字符串。

如果我能以另一种方式做到这一点,我会采取所有改进措施:)

这是我的代码:

#!/bin/bash
STA="start"
RES="restart"
STO="stop"
SERVERNAME="server_live"
if [ $1 -ge 1 ]
then
    echo "Entre un argument : start, stop, restart"
elif [ $1 = $STA ]
then
    screen -mdS $SERVERNAME
    screen -S $SERVERNAME -dm bash -c 'sleep 1;cd /home/cfx-server; bash run.sh;exec sh'
    echo "Serveur redémarré"
elif [ $1 = $RES ]
then
    screen -ls | grep $SERVERNAME | cut -d. -f1 | awk '{print $1}' | xargs kill
    screen -mdS $SERVERNAME
    screen -S $SERVERNAME -dm bash -c 'sleep 1;cd /home/cfx-server; bash run.sh;exec sh'
    echo "Serveur Restart"
elif [ $1 = $STO ]
then
    screen -ls | grep $SERVERNAME | cut -d. -f1 | awk '{print $1}' | xargs kill
    echo "Serveur Stoppé"
fi

我收到以下错误: My code here

这意味着:在不可预见的符号elif第10行附近出现语法错误

提前致谢..我想补充一下

#!/bin/bash
echo "read smthg"
read name

也出错(在阅读时),我怎么知道我是否有版本问题或类似的东西?

1 个答案:

答案 0 :(得分:0)

你应该使用case而不是if ... elif,并且(几乎)总是在“”之间引用你的变量:

请尝试此版本(靠近您的版本,但使用案例... esac并添加了一些引号):

#!/bin/bash
SERVERNAME="server_live"

case "$1" in
  start)
    screen -mdS "$SERVERNAME"
    screen -S "$SERVERNAME" -dm bash -c 'sleep 1;cd /home/cfx-server; bash run.sh;exec sh'
    echo "Serveur redémarré"
    ;;
  restart)
    screen -ls | grep $SERVERNAME | cut -d. -f1 | awk '{print $1}' | xargs kill
    screen -mdS "$SERVERNAME"
    screen -S "$SERVERNAME" -dm bash -c 'sleep 1;cd /home/cfx-server; bash run.sh;exec sh'
    echo "Serveur Restart"
    ;;
  stop)
    screen -ls | grep $SERVERNAME | cut -d. -f1 | awk '{print $1}' | xargs kill
    echo "Serveur Stoppé"
    ;;
  *)
    echo "argument: '$1' non reconnu..."
    exit 1
    ;;
esac

如果您遇到错误,您的脚本可能会包含干扰该部分之前的内容?请先将您的脚本粘贴到:www.shellcheck.net并查看它告诉您的内容(它将解析它并显示许多常见错误,例如未闭合的引号等)。

修改

问题来自于人在windows下编辑(使用'CR-LF'行结尾)并在linux / unix中使用它(预期只是LF,因此将CR作为一个额外的字符在包含它们的行。)

要删除脚本中未用于编写脚本的“所有不可打印的内容”:

LC_ALL="C" tr -cd "[$(printf '\t')\$(printf '\n') -~]" <script.bash >script_without_nonprintables.bash
  # LC_ALL="C" just before tr makes tr use that environment, which gives "ascii" instead of whatever locale you use. This helps ensure the ranges given are the ascii ones, and not something else.
  # -c = complement, ie "whatever is not..."   -d="delete", so -cd= "delete whatever is not specified"
  #  [a-d] = from a to d in the current locale (ascii, here, thanks to LC_ALL="C", so it will be : a, b, c or d
  #   in ascii,  SPACE to ~  covers all the character you need to write scripts, except for TAB (\t) and Newline (\n), so I added those as well.
  #   for newline, I preceded it with an "\" to have it taken literally
chmod +x script_without_nonprintables.bash