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
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!
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.
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!
Thanks for clearing that up! I thought it was necessary.
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.
Exactly! I learned this the hard way too. `exec` is really meant for when you want to replace the current script with another program.
Thanks for clarifying that! I always thought `exec` was just a standard way to run commands.