简单的退出脚本(if - then)

时间:2015-02-10 15:33:05

标签: linux

我对编程感到很伤心!我试图从术语脚本中做出一个非常基本的退出。基本上你运行scipt。然后它将询问您是否要退出终端或停留。当我选择1或2时,它只返回终端。

理想情况下,我想键入" logout"并且我会使用相同的选项获得相同的脚本,但我已经尝试了2天而且它没有意义。

谢谢你!

#! /bin/bash
# Created by Sarge on Feb. 9, 2015
#This script locks the screen when user logs out
# User must type "logout" and will then have to enter their password
# After the correct password for the user is enter
# the screen will go into lock mode

# clear the screen
clear

# exit options
echo "1. Exit"
echo "2. No"

# exit screen
echo "Exit terminal? (1 = Exit.  2 = No)."

# user input
read user_input

if [ $user_input = 1 ] ; then
    exit
elif [ $user_input = 2 ] ; then
    exit 0
fi

再次感谢你。

3 个答案:

答案 0 :(得分:1)

脚本在与交互式shell不同的进程中运行。因此,exit只会结束脚本。请注意,shell可能不是登录用户的内容,并且终止它不会注销用户(例如,当用户在他的shell中运行shell时)。如果它足以让你杀死shell,你可以运行kill $PPID

很难找到确切记录用户的内容。最好的近似方法是爬上进程树,直到父进程不再在您要注销的用户下运行,然后终止子进程(或者这个子树中的所有进程都确保没有任何生存)。您可以使用pstree来查看您需要执行的操作,并ps实际执行此操作。

答案 1 :(得分:0)

使用==而不是=运算符,如下所示:

if [ $user_input == 1 ] ; then
    exit
elif [ $user_input == 2 ] ; then
    exit 0
fi

您也可以选择将此替换为-eq,如下所示:

if [ $user_input -eq 1 ] ; then
    exit
elif [ $user_input -eq 2 ] ; then
    exit 0
fi

原因:

在大多数编程语言中,包括BASH,

  1. =被称为赋值运算符,它将右侧的值赋给左侧的变量
  2. ==是检查LHS和RHS是否相等的等式检查运算符,并根据比较结果返回true或false (这是在本程序的if条件中完成的。)

答案 2 :(得分:0)

弄清楚如何逃避关键词。在我的主目录中创建了一个bin文件夹。我把我的脚本放在bin中。比我尝试Alias =" end" ="退出"。现在当我输入"结束" (没有引号),我的脚本自动运行!!!呼叫声!