myshell-py 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
myshell/prompt.py ADDED
@@ -0,0 +1,197 @@
1
+ """The prompt: PS1 escapes and the default prompt."""
2
+ import getpass
3
+ import os
4
+ import socket
5
+ import sys
6
+ import time
7
+ from typing import List, Optional
8
+
9
+ from .state import ShellState
10
+
11
+ try:
12
+ import readline as _readline
13
+ # The libedit on macOS prints the text between \x01 and \x02 out of order, so no markers there.
14
+ MARKERS = not (sys.platform == "darwin" and "libedit" in (_readline.__doc__ or ""))
15
+ except ImportError:
16
+ MARKERS = True
17
+
18
+
19
+ # Prompt
20
+ #
21
+ # Set PS1 in ~/.myshellrc to change it. These escapes work, as in bash:
22
+ # \w current directory, with ~ for home \W last part of the directory
23
+ # \u user name \h host name \$ $ or # for root \j running jobs
24
+ # \n newline \e escape character \\ backslash
25
+ # \[ \] wrap colors so line editing counts the width correctly
26
+ # One extra escape: \? is the exit status of the last command.
27
+ # Time and git:
28
+ # \t time as 24-hour HH:MM:SS \T time as 12-hour HH:MM:SS \A time as HH:MM
29
+ # \@ time as 12-hour am/pm \d date, such as "Wed Nov 12"
30
+ # \g git branch of the current folder, empty outside a repository
31
+ # The default prompt shows the branch after the folder.
32
+ DEFAULT_PS1_COLOR = r"\[\e[1;32m\]\w\[\e[0m\] \$ "
33
+ DEFAULT_PS1_PLAIN = r"\w \$ "
34
+ FAILED_PREFIX_COLOR = r"\[\e[1;31m\][\?]\[\e[0m\] "
35
+ FAILED_PREFIX_PLAIN = r"[\?] "
36
+
37
+
38
+ def current_dir() -> str:
39
+ try:
40
+ return os.getcwd()
41
+ except OSError:
42
+ return os.environ.get("PWD", "?") # the directory was deleted
43
+
44
+
45
+ def now() -> time.struct_time:
46
+ """The current local time. Tests replace this function."""
47
+ return time.localtime()
48
+
49
+
50
+ def git_branch(start: Optional[str] = None) -> str:
51
+ """The branch of the git repository around `start`, or "" outside one. A detached head
52
+ shows the first seven characters of the commit. Reads .git directly, so git need not exist."""
53
+ path = start or current_dir()
54
+ for _ in range(64):
55
+ dot_git = os.path.join(path, ".git")
56
+ if os.path.isdir(dot_git):
57
+ git_dir = dot_git
58
+ elif os.path.isfile(dot_git):
59
+ try:
60
+ with open(dot_git, encoding="utf-8", errors="replace") as f:
61
+ text = f.read().strip()
62
+ except OSError:
63
+ return ""
64
+ if not text.startswith("gitdir:"):
65
+ return ""
66
+ git_dir = os.path.join(path, text[len("gitdir:"):].strip())
67
+ else:
68
+ parent = os.path.dirname(path)
69
+ if parent == path:
70
+ return ""
71
+ path = parent
72
+ continue
73
+ try:
74
+ with open(os.path.join(git_dir, "HEAD"), encoding="utf-8", errors="replace") as f:
75
+ head = f.read().strip()
76
+ except OSError:
77
+ return ""
78
+ if head.startswith("ref:"):
79
+ ref = head[4:].strip()
80
+ return ref[len("refs/heads/"):] if ref.startswith("refs/heads/") else ref
81
+ return head[:7]
82
+ return ""
83
+
84
+
85
+ def format_duration(seconds: float) -> str:
86
+ """2.3s, 45s, 3m 05s, 1h 02m."""
87
+ if seconds < 10:
88
+ return f"{seconds:.1f}s"
89
+ total = int(round(seconds))
90
+ if total < 60:
91
+ return f"{total}s"
92
+ minutes, secs = divmod(total, 60)
93
+ if minutes < 60:
94
+ return f"{minutes}m {secs:02d}s"
95
+ hours, minutes = divmod(minutes, 60)
96
+ return f"{hours}h {minutes:02d}m"
97
+
98
+
99
+ def slow_notice(state: ShellState) -> str:
100
+ """The text printed after a command that ran longer than SLOW_COMMAND_SECS
101
+ (default 2 seconds). Set the variable to 0 or off to turn it off."""
102
+ raw = state.get_variable("SLOW_COMMAND_SECS")
103
+ if raw is None:
104
+ limit = 2.0
105
+ else:
106
+ try:
107
+ limit = float(raw)
108
+ except ValueError:
109
+ return ""
110
+ if limit <= 0 or state.last_duration < limit:
111
+ return ""
112
+ return f"took {format_duration(state.last_duration)}"
113
+
114
+
115
+ def short_path(path: str) -> str:
116
+ home = os.environ.get("HOME", "").rstrip("/\\")
117
+ if home:
118
+ if path == home:
119
+ return "~"
120
+ for sep in {"/", os.sep}:
121
+ if path.startswith(home + sep):
122
+ return "~" + path[len(home):].replace(os.sep, "/")
123
+ return path
124
+
125
+
126
+ def expand_prompt(template: str, state: ShellState) -> str:
127
+ out: List[str] = []
128
+ i = 0
129
+ while i < len(template):
130
+ c = template[i]
131
+ if c != "\\" or i + 1 >= len(template):
132
+ out.append(c)
133
+ i += 1
134
+ continue
135
+ esc = template[i + 1]
136
+ i += 2
137
+ if esc == "w":
138
+ out.append(short_path(current_dir()))
139
+ elif esc == "W":
140
+ path = current_dir()
141
+ out.append("~" if short_path(path) == "~" else (os.path.basename(path) or "/"))
142
+ elif esc == "u":
143
+ try:
144
+ out.append(getpass.getuser())
145
+ except Exception:
146
+ out.append("user")
147
+ elif esc == "h":
148
+ out.append(socket.gethostname().split(".")[0])
149
+ elif esc == "$":
150
+ out.append("#" if hasattr(os, "geteuid") and os.geteuid() == 0 else "$")
151
+ elif esc == "j":
152
+ out.append(str(sum(1 for j in state.jobs.numbered() if not j.completed)))
153
+ elif esc == "?":
154
+ out.append(str(state.last_status))
155
+ elif esc in "tTA@d":
156
+ t = now()
157
+ out.append({"t": time.strftime("%H:%M:%S", t), "T": time.strftime("%I:%M:%S", t),
158
+ "A": time.strftime("%H:%M", t), "@": time.strftime("%I:%M %p", t),
159
+ "d": time.strftime("%a %b %d", t)}[esc])
160
+ elif esc == "g":
161
+ out.append(git_branch())
162
+ elif esc == "n":
163
+ out.append("\n")
164
+ elif esc == "e":
165
+ out.append("\x1b")
166
+ elif esc == "[":
167
+ out.append("\x01" if MARKERS else "") # readline: the text up to \] takes no screen width
168
+ elif esc == "]":
169
+ out.append("\x02" if MARKERS else "")
170
+ elif esc == "\\":
171
+ out.append("\\")
172
+ else:
173
+ out.append("\\" + esc)
174
+ return "".join(out)
175
+
176
+
177
+ def build_continuation_prompt(state: ShellState) -> str:
178
+ """The prompt for extra input lines, such as a here-document body. Set PS2 to change it."""
179
+ custom = state.get_variable("PS2")
180
+ return expand_prompt(custom if custom is not None else "> ", state)
181
+
182
+
183
+ def build_prompt(state: ShellState) -> str:
184
+ custom = state.get_variable("PS1")
185
+ if custom is not None:
186
+ return expand_prompt(custom, state)
187
+ color = "NO_COLOR" not in os.environ and os.environ.get("TERM", "") not in ("", "dumb")
188
+ template = DEFAULT_PS1_COLOR if color else DEFAULT_PS1_PLAIN
189
+ branch = git_branch()
190
+ if branch:
191
+ # The branch name goes in as plain text. A backslash in it must not act as an escape.
192
+ safe = branch.replace("\\", "\\\\")
193
+ shown = (r"\[\e[35m\](" + safe + r")\[\e[0m\]") if color else "(" + safe + ")"
194
+ template = template.replace(r" \$ ", " " + shown + r" \$ ")
195
+ if state.last_status != 0:
196
+ template = (FAILED_PREFIX_COLOR if color else FAILED_PREFIX_PLAIN) + template
197
+ return expand_prompt(template, state)
myshell/quiz.py ADDED
@@ -0,0 +1,148 @@
1
+ """Pip's quiz questions. Each topic matches a lesson key."""
2
+ import random
3
+ from dataclasses import dataclass
4
+ from typing import List, Optional
5
+
6
+
7
+ @dataclass
8
+ class Question:
9
+ topic: str
10
+ text: str
11
+ choices: List[str]
12
+ answer: int # index into choices
13
+ why: str
14
+
15
+
16
+ def q(topic: str, text: str, choices: List[str], answer: int, why: str) -> Question:
17
+ return Question(topic, text, choices, answer, why)
18
+
19
+
20
+ QUESTIONS: List[Question] = [
21
+ q("basics", "Which command shows the folder you are in?",
22
+ ["pwd", "cd", "echo", "ls"], 0, "pwd means print working directory."),
23
+ q("basics", "What does cd - do?",
24
+ ["Goes to your home folder", "Goes back to the previous folder", "Deletes a folder",
25
+ "Lists the folder"], 1, "cd - jumps to the folder you were in before."),
26
+ q("basics", "Which key completes a command or a file name?",
27
+ ["Enter", "Tab", "Esc", "Space"], 1, "Tab completes. Press it twice to see the choices."),
28
+ q("pipes", "What does a pipe (|) do?",
29
+ ["Saves output to a file", "Sends the output of one command into the next",
30
+ "Runs a command in the background", "Ends a command"], 1,
31
+ "a | b feeds the output of a into b."),
32
+ q("pipes", "Which operator adds text to the end of a file?",
33
+ [">", ">>", "<", "|"], 1, ">> appends. > replaces the file."),
34
+ q("pipes", "What does 2>&1 do?",
35
+ ["Sends error messages to the same place as normal output",
36
+ "Hides error messages", "Runs a command twice", "Reads input from file 2"], 0,
37
+ "File 2 is the error stream and file 1 is normal output."),
38
+ q("variables", "How do you read a variable called name?",
39
+ ["name", "$name", "#name", "(name)"], 1, "A dollar sign reads the value."),
40
+ q("variables", "What does echo $((6 * 7)) print?",
41
+ ["6 * 7", "13", "42", "67"], 2, "$(( )) does the math."),
42
+ q("variables", "What does $? hold?",
43
+ ["The current folder", "The exit status of the last command",
44
+ "The number of arguments", "The shell name"], 1, "0 means success. Anything else is a failure."),
45
+ q("quotes", "What does echo '$HOME' print?",
46
+ ["Your home folder", "$HOME", "Nothing", "An error"], 1,
47
+ "Single quotes keep every character as typed."),
48
+ q("quotes", "Why wrap a variable in double quotes?",
49
+ ["It runs faster", "It keeps spaces in the value together",
50
+ "It makes the variable global", "It deletes the variable"], 1,
51
+ "Without quotes the shell splits the value at spaces."),
52
+ q("logic", "When does the command after && run?",
53
+ ["Always", "When the first command fails", "When the first command succeeds",
54
+ "Never"], 2, "&& means and. || runs the next command after a failure."),
55
+ q("logic", "Which loop runs once for each item in a list?",
56
+ ["while", "for", "until", "if"], 1, "for NAME in LIST; do ...; done"),
57
+ q("logic", "What does break do inside a loop?",
58
+ ["Skips to the next round", "Leaves the loop", "Stops the shell", "Pauses the loop"], 1,
59
+ "continue skips to the next round. break leaves."),
60
+ q("jobs", "What does a trailing & do?",
61
+ ["Runs the command in the background", "Repeats the command",
62
+ "Hides the output", "Joins two commands"], 0, "The prompt returns at once."),
63
+ q("jobs", "Which key combination stops a running command?",
64
+ ["Ctrl+C", "Ctrl+D", "Ctrl+L", "Ctrl+A"], 0, "Ctrl+C sends an interrupt."),
65
+ q("customize", "Where do you put aliases so they load at every start?",
66
+ ["~/.myshellrc", "/etc/hosts", "~/Documents", "PATH"], 0,
67
+ "The rc file runs each time an interactive shell starts."),
68
+ q("customize", "Which prompt escape shows the current folder?",
69
+ [r"\w", r"\u", r"\h", r"\$"], 0, r"\u is the user name and \h is the host."),
70
+ q("functions", "How do you write the first argument inside a function?",
71
+ ["$0", "$1", "$#", "$@"], 1, "$1 is the first argument. $0 is the script name."),
72
+ q("functions", "What does $# hold?",
73
+ ["The last exit status", "The number of arguments", "All the arguments", "The process ID"],
74
+ 1, "$@ holds all the arguments."),
75
+ q("functions", "What does return 3 do in a function?",
76
+ ["Prints 3", "Leaves the function with status 3", "Repeats it 3 times", "Exits the shell"],
77
+ 1, "return ends the function and sets $? to the number."),
78
+ q("functions", 'What does "$@" give you?',
79
+ ["All arguments as one word", "Each argument as its own word", "The first argument",
80
+ "The count of arguments"], 1, 'The quotes keep each argument whole, even with spaces.'),
81
+ q("functions", "Which keyword gives a variable a value that only lives in the function?",
82
+ ["export", "local", "set", "unset"], 1, "local restores the old value when the function ends."),
83
+ q("expansion", "What does ${NAME:-fallback} give when NAME is unset?",
84
+ ["An error", "Nothing", "fallback", "NAME"], 2, ":- supplies a default."),
85
+ q("expansion", "What does ${#word} give when word is hello?",
86
+ ["hello", "5", "4", "0"], 1, "# in front asks for the length."),
87
+ q("expansion", "With f=notes.txt, what does ${f%.txt} give?",
88
+ ["notes", ".txt", "notes.txt", "txt"], 0, "% removes a matching ending."),
89
+ q("expansion", "With s=a-b-c, what does ${s//-/+} give?",
90
+ ["a+b-c", "a+b+c", "a-b-c", "+"], 1, "Two slashes replace every match. One replaces the first."),
91
+ q("expansion", "What does echo {1..4} print?",
92
+ ["{1..4}", "1 2 3 4", "1234", "4"], 1, "Brace expansion builds the list before the command runs."),
93
+ q("expansion", "What does echo file.{txt,md} print?",
94
+ ["file.{txt,md}", "file.txt file.md", "file.txtmd", "file."], 1,
95
+ "Each item in the braces makes one word."),
96
+ q("case", "What ends one arm of a case statement?",
97
+ ["fi", ";;", "done", "esac"], 1, "esac ends the whole case. ;; ends one arm."),
98
+ q("case", "Which pattern matches anything?",
99
+ ["?", "*", "%", "!"], 1, "A lone * as the last pattern works as a default."),
100
+ q("case", "How do you give one arm two patterns?",
101
+ ["a,b)", "a|b)", "a&b)", "a b)"], 1, "Separate the patterns with a pipe."),
102
+ q("tools", "Which builtin reads a line of input into a variable?",
103
+ ["read", "scan", "input", "get"], 0, "read NAME stores the line in NAME."),
104
+ q("tools", "Which command formats text with %s and %d?",
105
+ ["echo", "printf", "format", "print"], 1, "printf repeats its format for extra arguments."),
106
+ q("tools", "What does set -e do?",
107
+ ["Prints every command", "Stops the script when a command fails",
108
+ "Sets an error message", "Clears variables"], 1, "set -x prints every command. set -e stops on failure."),
109
+ q("tools", "What does trap 'echo bye' EXIT do?",
110
+ ["Runs echo now", "Runs echo when the shell ends", "Blocks Ctrl+C", "Defines a function"],
111
+ 1, "A trap runs its command when the signal or event arrives."),
112
+ q("tools", "Which command shows where a program lives?",
113
+ ["which", "where", "find", "path"], 0, "which prints the path, or says builtin, alias or function."),
114
+ q("prompt", r"Which escape shows the time as HH:MM:SS?",
115
+ [r"\t", r"\d", r"\w", r"\g"], 0, r"\d is the date and \g is the git branch."),
116
+ q("prompt", "How does the shell find the git branch?",
117
+ ["It runs git", "It reads the .git/HEAD file", "It asks the network", "It guesses"],
118
+ 1, "No git program is needed."),
119
+ q("prompt", "Which variable sets how many seconds make a command slow?",
120
+ ["SLOW_COMMAND_SECS", "SLOW", "TIMEOUT", "PS1"], 0, "Set it to off to hide the time notice."),
121
+ q("typing", "Which key opens reverse history search?",
122
+ ["Ctrl+R", "Ctrl+S", "Ctrl+H", "Ctrl+T"], 0, "Type part of an old command and it appears."),
123
+ q("typing", "Which key accepts the grey suggestion?",
124
+ ["Right arrow", "Left arrow", "Delete", "Tab twice"], 0, "End works too."),
125
+ ]
126
+
127
+
128
+ def topics() -> List[str]:
129
+ seen: List[str] = []
130
+ for item in QUESTIONS:
131
+ if item.topic not in seen:
132
+ seen.append(item.topic)
133
+ return seen
134
+
135
+
136
+ def pick(count: int, topic: Optional[str] = None,
137
+ rng: Optional[random.Random] = None) -> List[Question]:
138
+ """Choose count questions. With a topic, only that topic. Order and choices are shuffled."""
139
+ rng = rng or random.Random()
140
+ pool = [x for x in QUESTIONS if topic in (None, x.topic)]
141
+ chosen = rng.sample(pool, min(count, len(pool)))
142
+ shuffled = []
143
+ for item in chosen:
144
+ order = list(range(len(item.choices)))
145
+ rng.shuffle(order)
146
+ shuffled.append(Question(item.topic, item.text, [item.choices[i] for i in order],
147
+ order.index(item.answer), item.why))
148
+ return shuffled
myshell/state.py ADDED
@@ -0,0 +1,107 @@
1
+ """Shell state: aliases, variables, jobs, history and the last exit status."""
2
+ import os
3
+ import sys
4
+ import subprocess
5
+ from dataclasses import dataclass, field
6
+ from typing import TYPE_CHECKING, Callable, Dict, List, Optional, Set, TextIO
7
+
8
+ from . import history
9
+ from .paths import home_file
10
+ from .jobs import JobControl
11
+
12
+ if TYPE_CHECKING:
13
+ from .executor import Executor
14
+
15
+
16
+ @dataclass
17
+ class ShellState:
18
+ aliases: Dict[str, str] = field(default_factory=dict)
19
+ jobs: JobControl = field(default_factory=JobControl)
20
+ background_jobs: List[subprocess.Popen] = field(default_factory=list) # portable path only
21
+ history_file: str = field(default_factory=lambda: home_file(".custom_shell_history"))
22
+ rc_file: str = field(default_factory=lambda: home_file(".myshellrc"))
23
+ last_status: int = 0
24
+ variables: Dict[str, str] = field(default_factory=dict) # shell variables, not exported
25
+ executor: Optional["Executor"] = None
26
+ missing_command: Optional[str] = None # set when a lone command was not found
27
+ loop_depth: int = 0 # loops running right now. break and continue need one
28
+ stdin: Optional[TextIO] = None # input stream for the builtin that runs now. None means sys.stdin
29
+ functions: Dict[str, list] = field(default_factory=dict) # name -> body (a list of ListItem)
30
+ positional: List[str] = field(default_factory=list) # $1, $2, ... of the current function or script
31
+ script_name: str = "myshell" # $0
32
+ func_depth: int = 0 # functions and sourced files running right now. return needs one
33
+ local_frames: List[Dict[str, Optional[str]]] = field(default_factory=list) # saved values for `local`
34
+ options: Set[str] = field(default_factory=set) # set -e, -u, -x as "errexit", "nounset", "xtrace"
35
+ no_errexit: int = 0 # above 0 while a condition runs, where a failure must not stop the script
36
+ traps: Dict[str, str] = field(default_factory=dict) # signal name or EXIT -> command text
37
+ pending_traps: List[str] = field(default_factory=list) # signals caught, not yet handled
38
+ keep_going: bool = False # tests and the guide set this so an expansion error never ends the shell
39
+ last_duration: float = 0.0 # seconds the last interactive command took
40
+ progress_file: str = field(default_factory=lambda: home_file(".myshell_progress.json"))
41
+
42
+ def input_stream(self) -> TextIO:
43
+ """Where a builtin reads its input: a redirect or pipe if there is one, else the terminal."""
44
+ import sys
45
+ return self.stdin if self.stdin is not None else sys.stdin
46
+
47
+ # --- variables ---
48
+ # Exported variables live in os.environ, so child processes inherit them.
49
+ def get_variable(self, name: str) -> Optional[str]:
50
+ if name in self.variables:
51
+ return self.variables[name]
52
+ return os.environ.get(name)
53
+
54
+ def set_variable(self, name: str, value: str) -> None:
55
+ if name in os.environ:
56
+ os.environ[name] = value # an exported variable stays exported
57
+ else:
58
+ self.variables[name] = value
59
+
60
+ def export_variable(self, name: str, value: Optional[str] = None) -> None:
61
+ if value is None:
62
+ if name in self.variables:
63
+ os.environ[name] = self.variables.pop(name)
64
+ else:
65
+ self.variables.pop(name, None)
66
+ os.environ[name] = value
67
+
68
+ def unset_variable(self, name: str) -> None:
69
+ self.variables.pop(name, None)
70
+ os.environ.pop(name, None)
71
+
72
+ def execute(self, line: str, read_line: Optional[Callable[[], Optional[str]]] = None) -> int:
73
+ """Run one line in this shell. Used by source, scripts and $(...).
74
+ read_line supplies the lines of a here-document body."""
75
+ return self.executor.run_line(line, read_line)
76
+
77
+ def run_pending_traps(self) -> None:
78
+ """Run the trap commands for signals caught since the last check."""
79
+ while self.pending_traps:
80
+ cmd = self.traps.get(self.pending_traps.pop(0))
81
+ if cmd:
82
+ saved = self.last_status
83
+ try:
84
+ self.execute(cmd)
85
+ finally:
86
+ self.last_status = saved
87
+
88
+ def reap_jobs(self) -> None:
89
+ self.jobs.notify()
90
+ for job in self.background_jobs[:]:
91
+ if job.poll() is not None:
92
+ print(f"[Done] {job.args}")
93
+ self.background_jobs.remove(job)
94
+
95
+ def load_history(self) -> None:
96
+ history.set_limit()
97
+ try:
98
+ history.read(self.history_file)
99
+ except (OSError, ValueError):
100
+ pass
101
+
102
+ def save_history(self) -> None:
103
+ try:
104
+ history.write(self.history_file)
105
+ except Exception as e:
106
+ if os.environ.get("MYSHELL_DEBUG"):
107
+ print(f"history not saved: {e!r}", file=sys.stderr)
@@ -0,0 +1,195 @@
1
+ Metadata-Version: 2.5
2
+ Name: myshell-py
3
+ Version: 0.2.0
4
+ Summary: A Unix-style shell written in Python, with a built-in guide.
5
+ License: MIT
6
+ Keywords: education,shell,terminal
7
+ Classifier: Environment :: Console
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Topic :: System :: Shells
10
+ Requires-Python: >=3.9
11
+ Requires-Dist: prompt-toolkit>=3.0.36
12
+ Provides-Extra: dev
13
+ Requires-Dist: pyflakes>=3.0; extra == 'dev'
14
+ Requires-Dist: pytest>=7.0; extra == 'dev'
15
+ Description-Content-Type: text/markdown
16
+
17
+ # myshell
18
+
19
+ A Unix-style shell written in Python. It runs on Linux and macOS with full job control. It also runs on Windows through a simpler fallback.
20
+
21
+ ## Requirements
22
+
23
+ - Python 3.9 or newer. Tested on 3.9 and 3.13 on Linux, macOS and Windows (see `.github/workflows/ci.yml`).
24
+ - `prompt_toolkit` is optional. With it you get Ctrl+R history search, grey suggestions and syntax colors. Without it the shell uses plain `input()` and readline.
25
+ - pytest and pyflakes for development: `pip install -e ".[dev]"`
26
+
27
+ ## Install and run
28
+
29
+ uvx myshell run without installing (after the first release)
30
+ uv tool install myshell install it
31
+ pip install myshell
32
+
33
+ From a clone:
34
+
35
+ python shell.py interactive shell
36
+ python shell.py -c "echo hi" run one command string
37
+ python shell.py script.sh a b run a script. $1 is a, $2 is b
38
+ python -m myshell same thing, as a package
39
+ uv run myshell uses pyproject.toml
40
+
41
+ `myshell -c 'cmd' NAME ARG...` sets `$0` to NAME and `$1...` to the ARGs.
42
+
43
+ ## Run the tests
44
+
45
+ pip install -e ".[dev]"
46
+ python -m pytest
47
+ python -m pyflakes myshell tests
48
+
49
+ With uv: `uv run --extra dev pytest`.
50
+
51
+ ## Release
52
+
53
+ uv build writes dist/*.whl and dist/*.tar.gz
54
+ uv publish needs a PyPI token or trusted publishing
55
+
56
+ Pushing a tag such as `v0.2.0` runs `.github/workflows/release.yml`, which builds and publishes with trusted publishing. Add the repository as a trusted publisher on pypi.org first (project `myshell`, workflow `release.yml`, environment `pypi`). Bump `version` in `pyproject.toml` before each release. If the name `myshell` is taken when you publish, change `name` in `pyproject.toml`. The command stays `myshell`.
57
+
58
+ ## Features
59
+
60
+ Commands and operators
61
+
62
+ - Pipes: `a | b`
63
+ - Lists: `a; b`, `a && b`, `a || b`
64
+ - Background jobs: `a &`
65
+ - Comments with `#`
66
+
67
+ Quoting and expansion
68
+
69
+ - Single quotes, double quotes and backslash escapes
70
+ - Variables: `$X`, `${X}`, `$?`, `$$`, and `$0 $1 ... $# $@ $*`
71
+ - Parameter expansion: `${X:-default}` `${X:=v}` `${X:?msg}` `${X:+alt}` `${#X}` `${X%.txt}` `${X%%p}` `${X#p}` `${X##p}` `${X/old/new}` `${X//old/new}` `${X:off:len}` `${X^^}` `${X,,}`
72
+ - Brace expansion: `file.{txt,md}`, `{1..5}`, `{a..e}`, `{01..10}`, `{1..10..2}`
73
+ - Command substitution: `$(cmd)` and backticks
74
+ - Arithmetic: `$((1 + 2 * x))`, including `+=`, `?:`, hex and octal
75
+ - Word splitting, globbing (`*`, `?`, `[ab]`) and tilde (`~`)
76
+ - Assignments: `NAME=value`, and `NAME=value cmd` for one command
77
+
78
+ Redirection
79
+
80
+ - `< > >> 2> 2>> &> &>>`
81
+ - `2>&1` and `1>&2`, applied left to right
82
+ - Here-strings: `<<<`
83
+ - Here-documents: `<<EOF` and `<<-EOF`. A quoted delimiter such as `<<'EOF'` turns expansion off.
84
+
85
+ Control flow
86
+
87
+ - `if`, `elif`, `else`, `fi`
88
+ - `while`, `until`, `for NAME in WORDS`, with `do` and `done`. A bare `for x; do` loops over `"$@"`.
89
+ - `case WORD in a|b) ...;; *.txt) ...;; *) ...;; esac`
90
+ - Functions: `name() { ...; }` or `function name { ...; }`, with `$1`, `$@`, `$#`, `return` and `local`
91
+ - Groups: `{ a; b; }`
92
+ - `break N` and `continue N`
93
+ - Blocks work on one line or across many lines
94
+
95
+ Builtins
96
+
97
+ - `echo` (with `-n -e -E`), `pwd cd exit alias unalias type which export unset source .`
98
+ - `read` (`-r -p -d -n`), `printf` (`-v`), `set` (`-e -u -x`, `-o`, `--`), `shift local return`
99
+ - `env` (`-i -u NAME=value`), `exec`, `trap` (EXIT, INT, TERM, HUP, USR1, USR2)
100
+ - `true false :`
101
+ - `jobs fg bg wait`
102
+ - `test` and `[ ]`: file, string and number checks, and `!`
103
+ - `history`: `N`, `-c`, `-d N`, `-w [file]`, `-r [file]`
104
+ - `guide`: lessons, cheat sheet and tips
105
+
106
+ Commands that work on every system
107
+
108
+ - `ls cat head tr sleep mkdir rm cp mv touch wc grep` are built in. A real program of the same name on your PATH wins, so on Linux and macOS you still get GNU or BSD tools. Where there is none (plain Windows), the built-in one runs. Set `MYSHELL_PORTABLE=1` to always use the built-in ones.
109
+ - They also work in pipes and `$(...)` without fork. This is what makes Pip's lessons run on Windows.
110
+
111
+ Interactive use
112
+
113
+ - Job control: Ctrl+C, Ctrl+Z, `fg`, `bg`
114
+ - Tab completion for commands, paths and function names
115
+ - With `prompt_toolkit`: Ctrl+R reverse search, grey suggestion from history (Right arrow or End takes it), colors (green known command, red unknown, yellow strings, cyan variables). `MYSHELL_EDITOR=basic` turns it off.
116
+ - After a command that takes longer than 2 seconds the shell prints `took 3.2s`. Set `SLOW_COMMAND_SECS` to change the limit, or to `off`.
117
+ - Traps: `trap 'cmd' EXIT` runs when the shell ends
118
+ - History saved in `~/.custom_shell_history`, limited to 1000 entries
119
+ - Startup file `~/.myshellrc`
120
+ - Prompt set with `PS1`. Continuation lines use `PS2`.
121
+
122
+ ## Pip, the guide
123
+
124
+ Pip is a small original character who lives in the shell.
125
+
126
+ ,---. .--------------------------------------.
127
+
128
+ ( ^ ^ ) | Hi, I am Pip, your shell guide. |
129
+ \ v / '--------------------------------------'
130
+ (_@_)>
131
+
132
+ - Greets you at startup with a tip. Only on a real terminal.
133
+ - `guide` opens a menu of 13 lessons, with `[x]` next to the ones you finished. Each step shows a command. Press Enter to run it, `s` to skip, `q` to stop.
134
+ - `guide TOPIC` jumps to one lesson. Names and numbers both work, for example `guide pipes` or `guide 2`.
135
+ - `guide cheat` prints a cheat sheet. `guide tip` prints one tip. `guide list` lists the topics.
136
+ - `guide quiz [TOPIC] [N]` asks N multiple-choice questions (default 5). `guide progress` shows finished lessons and best scores. `guide progress reset` clears them. Progress lives in `~/.myshell_progress.json`.
137
+ - Explains mistakes. A mistyped command gets "Did you mean ...?". An unclosed quote, `$(` or block gets a plain explanation.
138
+ - `guide off` hides Pip for the session. Put `GUIDE=off` in `~/.myshellrc` to hide Pip always.
139
+ - Scripts, `-c` and piped input never show Pip's greeting or hints.
140
+
141
+ ## Prompt escapes
142
+
143
+ | Escape | Meaning |
144
+ | ------------------------ | ------------------------------------------------------------ |
145
+ | `\w` | current directory, `~` for home |
146
+ | `\W` | last part of the directory |
147
+ | `\u` `\h` | user name, host name |
148
+ | `\$` | `$`, or `#` for root |
149
+ | `\j` | running jobs |
150
+ | `\?` | exit status of the last command |
151
+ | `\n` `\e` `\\` | newline, escape, backslash |
152
+ | `\t` `\T` `\A` `\@` `\d` | time (24-hour, 12-hour, HH:MM, am/pm), date |
153
+ | `\g` | git branch of the current folder, empty outside a repository |
154
+ | `\[` `\]` | wrap colors so line editing counts width correctly |
155
+
156
+ The default prompt adds the branch in brackets inside a git repository.
157
+
158
+ Example `~/.myshellrc`:
159
+
160
+ PS1='\u@\h \W \$ '
161
+ PS2='more> '
162
+ alias ll='ls -l'
163
+
164
+ ## Layout
165
+
166
+ | File | Job |
167
+ | -------------------------- | ------------------------------------------------------------ |
168
+ | `cli.py` | entry point, interactive loop |
169
+ | `lexer.py` | text to tokens |
170
+ | `parser.py` | tokens to a tree |
171
+ | `expand.py` | variables, substitution, math, globbing |
172
+ | `arith.py` | the `$((...))` evaluator |
173
+ | `heredoc.py` | here-document bodies |
174
+ | `executor.py` | runs the tree with fork and pipes |
175
+ | `jobs.py` | process groups and job control |
176
+ | `builtins.py` | core builtin commands, lookup of builtins |
177
+ | `more_builtins.py` | read, printf, set, env, which, trap, exec and friends |
178
+ | `coreutils.py` | ls, cat, head, tr, sleep, mkdir, rm, cp, mv, touch, wc, grep |
179
+ | `editor.py` `highlight.py` | optional prompt_toolkit line editor and syntax colors |
180
+ | `progress.py` `quiz.py` | Pip's progress file and quiz questions |
181
+ | `completion.py` | tab completion |
182
+ | `prompt.py` | prompt escapes |
183
+ | `guide.py` | Pip: lessons, hints, greeting |
184
+ | `state.py` | variables, aliases, history, status |
185
+ | `compat.py` | platform checks |
186
+
187
+ ## Limits
188
+
189
+ - Only file descriptors 0, 1 and 2 are redirected.
190
+ - Here-documents do not work inside multi-line `if`, loop and function blocks.
191
+ - Pipes, redirects and `&` after `fi`, `done`, `esac` or `}` are errors. So `cmd | while read x; do ...; done` does not work yet.
192
+ - Function bodies must be `{ ...; }` groups. There are no arrays, `eval`, `select` or `[[ ]]`.
193
+ - `test` has no `-a`, `-o` or parentheses.
194
+ - On Windows there is no job control: `&` runs in the foreground and `fg`, `bg` and `wait` are unavailable. Pipelines that include built-in commands run one stage after the other, with each stage's output held in memory.
195
+ - Signal traps run at the next command boundary, not in the middle of a command.