Shell script setup
Good practices
Use sh
If you do not need bash
features, then use sh
, it is installed on every UNIX-like system.
#!/bin/sh
Exit on failure
Shell scripts continue even if a commend returns error. To fail right away use:
set -e
Trap C-c
Catch Control-c and exit.
trap 'exit 128' INT
Use script directory
Assume we are executing a script from directory /Admin
, where /
is the root of a given project directory.
script_path="${0}"
script_root="$(dirname "${script_path}")"
We can use ${script_root}
to call other scripts form the Admin
directory, but we can also use it to relate to the /
.
project_root="$(realpath "${script_root}/../")"
echo "[INFO] Entering directory: ${project_root}"
cd "${project_root}"
So with above we can run commands form /
(repository root). Like for example make
and other:
make
python3 ./Admin/serve_1.py
Even better
Use Python for repository maintenance scripts.
from os import chdir
from os import path
from subprocess import run
from sys import argv
script_path = path.realpath(__file__)
script_root = path.dirname(script_path)
project_root = path.realpath(path.join(script_root, ".."))
print(f" * Entering directory: {project_root}")
chdir(project_root)
leftover_args = argv[1::]
command_arguments = ["make"] + leftover_args
cmd_string = " ".join(command_arguments)
print(f" * Executing command: {cmd_string}")
run(command_arguments, check=True)