Linux exit command does nothing

时间:2018-12-03 13:12:04

标签: linux bash

I'm new to Linux and am trying to create a simple program that checks if a user exists, if exists - exits the terminal, if not - creates it. I think I've done everything except exiting the terminal.

This is my code so far:

#!/bin/bash
user_name=newUser

if [ $(getent passwd $user_name) ]
then
    echo "User $user_name already exists!"
    exit
else
    echo "The user $user_name doesn't exist and will be added"
    sudo useradd -d /home/mint/newUser $user_name
fi

edit: As I said i'm new to Linux. Can someone edit my code and post it, I need to add it to a script, maybe i can close it with while function?

2 个答案:

答案 0 :(得分:2)

The exit command simply exits the current script. If you want to exit the terminal, you need to exit (or otherwise terminate) the program which is running in that terminal.

A common way to accomplish this is to make the process which wants to exit run as a function in your interactive shell.

add_user () { /path/to/your/script "$@" || exit; }

In this case, though, I would simply advise you to keep your script as is, and leave it to the user to decide whether or not they want to close their terminal.

By the way, the construct

if [ $(command) ]

will be true if the output from command is a non-empty string. The correct way to check the exit code from command is simply

if command

possibly with output redirection if you don't want the invoking user to see any output from command.

The function above also requires your scripit to exit with an explicit error; probably change it to exit 1 to explicitly communicate an error condition back to the caller.

#!/bin/bash
# First parameter is name of user to add
user_name=$1

# Quote variable; examine exit code
if getent passwd "$user_name" >/dev/null 2>&1
then
    # Notice addition of script name and redirect to stderr
    echo "$0: User $user_name already exists!" >&2
     # Explicitly exit with nonzero exit code
    exit 1
else
    # script name & redirect as above
    echo "$0: The user $user_name doesn't exist and will be added" >&2
    # Quote argument
    sudo useradd -d /home/mint/newUser "$user_name"
fi

答案 1 :(得分:-1)

This has been answered on askubuntu.com. I will summarise here:

In your script, as you may have noticed, exit will only exit the current script.

A user-friendly way to achieve what you're after is to use the exit command to set a suitable return code and call your script like ./<script> && exit.

If you really want the hard way, use

kill -9 $PPID

which will attempt to kill the enclosing process.