I have a bash script
my_script.sh created as a root user that has a part where it has to be switched to a sudo user.
I have tried heredocs and it's working, but the issue with it is I can't use variables to and fro with the bash script.
#!/usr/bin/bash #Name of my Script is my_script read -p "Enter hostname : " hostname hostnamectl set-hostname $hostname whoami sudo -i -u my_username bash << 'EOF' whoami mkdir ~/.ssh chmod 700 ~/.ssh nano ~/.ssh/authorized_keys read -p "Enter Database Name : " dbname echo "Database $dbname has been added to system!" EOF
The problem with this approach is I can't use the variable
$hostname inside heredocs if I use 'EOF' and if I don't use 'EOF' then I won't be able to use other variables e.g.
$dbname created inside heredocs.
I am trying the approach mentioned here
#!/usr/bin/bash if [ $(id -u) -eq 0 ]; then user=$1 dir=$2 cd "$dir" exec su "$user" "$0" -- "$@" fi whoami
On the terminal:
sh: 0: Can't open ./my_script.sh
my_username has sudo privileges.
System info: Ubuntu 20.04
How do I work out the error?