Python scripting

Bash scripts are fine if your script is not complicated. But Bash is ugly and if you try for example to use arrays/lists in Bash, you probably should just use Python for what are trying to accomplish with your Bash script.

You can use what you have learned about running programs and feed Python with commands that it can run:

>>> import subprocess

>>> proc = subprocess.run(["ls", "student"])
(…)
CompletedProcess(args=['ls', '/home/student'], returncode=0)

>>> proc.returncode
0

>>> proc = subprocess.run("ls /home/student", shell=True)
(…)
CompletedProcess(args='ls /home/student', returncode=0)

>>> proc = subprocess.run("ls /home/student", shell=True, capture_output=True, text=True)
CompletedProcess(args='ls /home/student', returncode=0, stdout='(…)', stderr='')

>>> proc.stdout
(…)

>>> proc.stderr

>>> proc = subprocess.run("ls /home/nonexistent", shell=True, capture_output=True, text=True)
CompletedProcess(args='ls /home/nonexistent', returncode=2, stdout='', stderr="ls: cannot access '/home/nonexistent': No such file or directory\n")

>>> proc = subprocess.run("ls /home/nonexistent", shell=True, capture_output=True, text=True, check=True)
---------------------------------------------------------------------------
CalledProcessError                        Traceback (most recent call last)
(…)

The most used modules when writing system scripts with Python are pathlib, os, shutil.

>>> from pathlib import Path
>>> p = Path.home() / "day_5"
PosixPath('/home/student/day_5')

>>> p.is_dir()
(…)

>>> p.is_file()
(…)

>>> p.exists()
(…)

>>> p.chmod(0o700)
(…)

>>> rel = Path(".")
PosixPath('.')

>>> rel.resolve()
PosixPath('/home/student/(…)')