How do I continue executing commands after an if statement in my bash script?

0
5
Asked By BubblyCactus42 On

Hey everyone, I'm new to bash scripting and I'm having a little trouble with my script. Here's what I have so far:

```bash
#!/bin/bash
set -x #;)
read user
if [[ -n $user ]]; then
exec adduser $user
else
exit 1
fi
mkdir $HOME/$user && chown $user
mkdir -p $HOME/$user/{Commun,Work,stuff}
```

I'm confused because the commands after the `if` statement aren't being executed. Can anyone explain why this is happening? Thanks in advance!

4 Answers

Answered By SmartyPantsPenguin On

Another suggestion is to just check if the user exists before calling `adduser`. That way you can avoid some common pitfalls. Here's a revised version of your script:
```bash
#!/bin/bash
set -x
read -p "Enter username: " user
if id "$user" >/dev/null; then
echo "User '$user' already exists."
else
sudo adduser "$user"
fi
```
Just make sure the home directory checks exist as well!

Answered By LogicalFox77 On

Your understanding of `exec` seems to be the core issue here. The `exec` command essentially replaces your current process with whatever command you run, in this case, `adduser`. So, to run subsequent commands, just omit `exec` and it should work fine.

CuriousHedgehog99 -

Thanks for clarifying that! I always thought `exec` was just a standard way to run commands.

Answered By SassyPanda15 On

Remember, using `exec` in a script doesn’t do what most people think it does. If you just want to run a command, leave it out. Just run `adduser` normally!

ConfusedKoala33 -

Thanks for clearing that up! I thought it was necessary.

Answered By CraftySquirrel88 On

The issue you’re facing is because of the `exec` command in your script. When you use `exec adduser $user`, it replaces the current shell process with the `adduser` process, which means that any commands after this line won't run because the shell is gone! You should just call `adduser $user` without `exec` to keep the shell running and execute further commands afterward.

GigglingTulip21 -

Exactly! I learned this the hard way too. `exec` is really meant for when you want to replace the current script with another program.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.