Yes, you can save a variable in a new variable almost as you show, but without the spaces in both bash
and zsh
:
username=$USER
I don't know what you are trying to do since there is no information in the question, but note that sudo
sets the SUDO_USER
variable to the value of $USER
when it was launched:
$ sudo sh -c 'echo "user:$USER sudo_user:$SUDO_USER"'
user:root sudo_user:terdon
Now that you have shared the script, you also need to fix some other things. echo ~/.zshrc > "alias "vim"="nvim""
will echo the string ~/.zshrc
into file named alias vim=nvim
. Presumably, you want to echo alias vim="nvim"
into ~/.zshrc
instead. This is a really, really bad idea of course, since it will keep on adding this line every time you run, so you might want to first check for the presence of the line before echoing it.
Next, you can indeed use SUDO_USER
to get the original user name. However, this is all kind of pointless since after the sudo -i
, no other command will be executed until you exit the sudo -i
shell. If you just want to authenticate, you only need to do that once unless your sudo
isn't set up to remember the password for even a few seconds (but then, sudo -i
won't work any better). See https://unix.stackexchange.com/a/579447/22222 for details on how to change the sudo
timeout so you don't need to enter the password multiple times.
Finally, you don't actually need to store the user: you are only running a few, specific commands with sudo (good!) so the chsh
would be running as the original user anyway. What's more, the ohmyzsh
install script already offers to make zsh your default shell so you don't need the chsh
command at all.
Putting all that together:
#!/bin/bash
#Install ZSH
sudo dnf install zsh -y
#Install oh-my-zsh
sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
#Install starship
sudo dnf install starship
#Export variables & aliases
lines=("alias vim='nvim'" "alias ..='cd ..'"
"alias lsblk='lsblk -e 7"
"eval "$(starship init zsh)"" )
for line in "${lines[@]}"; do
grep -q "$line" ~/.zshrc || printf '%s\n' "$line" >> ~/.zshrc
done
Change user's shell to zsh. This isn't needed, you can simply answer
yes when prompted by the ohmyzsh installation script.
chsh -s /bin/zsh $USER