I am writing a bash script to handle the installation of a repository, mostly it checks some basic dependencies and calls git clone often.

When running this script I want to perform a check to whether files have been installed or not.

git clone https://github.com/reticulatedpines/magiclantern_simplified.git 
echo "Exit status: ($?)" 
if [ $? -eq 0 ]; then
    echo "Magic Lantern has been cloned into ${ML_PATH}."
    exit 1

The problem is that the repository will clone into whatever the present working directory is which is not what I want and if I try cd ~ to return to the home directory it actually sends me to the root shell:

root@debian:~# (repository installs here).

How can I avoid this?

  • 1
    It is fairly common practice to assume that the working directory should not need to be changed, and then instead cd to the correct directory before executing the script. Most standard command act like this. If you know what the absolute path is to the working directory, you could use that in the script, e.g. cd ~theuser/the/dir. I believe the missing piece of info in the question is where you tell us exactly how you run your script (via root's cron, or via sudo, or in some other manner).
    – Kusalananda
    Commented Sep 11, 2022 at 6:32
  • 3
    in [ $? -eq 0 ], you're checking the exit status of [ which will be successful if echo succeeded. Use if git...; then echo success; else echo "failure (status = $?"; fi Commented Sep 11, 2022 at 6:35
  • This may be relevant: How to get the name of the user who executed a bash script as sudo?
    – Kusalananda
    Commented Sep 11, 2022 at 6:37
  • 5
    Why would you clone a source code repository as root? root is to make administrative tasks, not development, not compiling code. Only a make install or equivalent as the last stage after building might need to be made as root if it needs to install files in system locations or more generally needs to make changes to the system. Commented Sep 11, 2022 at 6:39
  • 3
    You do not want to run a script like this as root. If -- big IF -- you must do privileged things within your script, then only do those very specific things with privilege. For example, run your script as a regular user, but use "sudo apt install" within the script if it's a must. I would still recommend against it. It's just bad practice to do everything on a system as root and in many, many cases it's completely unnecessary. Unfortunately the linux culture has evolved in a way where people think they must do everything with sudo.
    – mikem
    Commented Sep 11, 2022 at 7:15

1 Answer 1

sudo -E <cmd>

running sudo with -E " preserve user environment when running command"

Preserving the user environment will run the command in the current location.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .