From running commands to building reliable Linux tools: shebang, variables, command substitution, quoting, arguments, and wrapper patterns.
This lab turns a small real wrapper script into a full shell-scripting mental model.
The main idea is that shell scripting is often not about writing a large program.
It is about building a reliable interface that connects commands, files, paths, and user input.
The original wrapper-focused material is preserved, and a new workstation module extends the same ideas
into .bashrc, PATH construction, environment variables, NVM, aliases, and Bash completion.
#!/bin/sh
# Convenience wrapper for Linux command helper.
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
python3 "$SCRIPT_DIR/linux_cmd_tool_v2_1.py" quick "$@"
A shell script is a small automation layer that connects commands together.
Think:
β’ Shell = glue / interface / orchestration
β’ Python = logic / data processing / engine
β’ Filesystem = where tools and data live
| Question | Shell concept | Example |
|---|---|---|
| Who runs this script? | Shebang | #!/bin/sh |
| Where is this script located? | $0 + dirname + pwd | SCRIPT_DIR=... |
| How do I store a value? | Variable assignment | SCRIPT_DIR="..." |
| How do I run a command and capture output? | Command substitution | $(pwd) |
| How do I pass user input forward? | Arguments | "$@" |
| How do I avoid path bugs? | Absolute path from script directory | python3 "$SCRIPT_DIR/tool.py" |
User types a simple command β shell wrapper receives it β Python tool processes it β output helps your work.
This is exactly how a personal CLI system starts.
#!/bin/sh
# Convenience wrapper for Linux command helper.
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
python3 "$SCRIPT_DIR/linux_cmd_tool_v2_1.py" quick "$@"
It lets you type:
linuxcmd usb
and internally translates it into:
python3 /path/to/linux_cmd_tool_v2_1.py quick usb
#!/bin/sh
This tells Linux:
βRun this file using /bin/sh.β
Without it, the script may run under whatever shell called it, which is less predictable.
| Choice | Meaning | Use case |
|---|---|---|
| #!/bin/sh | POSIX shell, portable | Portable Linux environments, simple wrappers |
| #!/bin/bash | Bash shell, more features | When you need bash-only syntax |
| #!/usr/bin/env python3 | Run Python from PATH | Python scripts |
For portable shell scripts, start with #!/bin/sh unless you really need Bash-specific features.
# Convenience wrapper for Linux command helper.
Lines starting with # are comments. They are ignored by the shell.
Good comments explain why the script exists, not just what each command does.
SCRIPT_DIR="..."
Shell variables are simple strings.
Important:
β’ No spaces around =
β’ Use quotes around values
β’ Read the value with $SCRIPT_DIR
| Correct | Wrong | Why |
|---|---|---|
| SCRIPT_DIR="/usr/local/bin" | SCRIPT_DIR = "/usr/local/bin" | Spaces around = break assignment |
| echo "$SCRIPT_DIR" | echo $SCRIPT_DIR | Unquoted version can break on spaces |
| python3 "$SCRIPT_DIR/tool.py" | python3 $SCRIPT_DIR/tool.py | Quoted version is safer |
VALUE="$(command)"
$(...) means:
1) run the command inside
2) capture its printed output
3) store/use that output as text
CURRENT_DIR="$(pwd)"
echo "$CURRENT_DIR"
Always prefer:
VALUE="$(command)"
instead of:
VALUE=$(command)
The quoted version is safer if output contains spaces.
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
| Piece | Meaning |
|---|---|
| $0 | Path used to call the script |
| dirname -- "$0" | Extract directory part of the script path |
| cd -- "$(dirname -- "$0")" | Move into the script directory |
| pwd | Print the absolute path |
| CDPATH= | Disable CDPATH side effects so cd behaves predictably |
| && | Only run pwd if cd succeeded |
Compute the absolute directory where this wrapper script lives, then store it in SCRIPT_DIR.
Without SCRIPT_DIR, the wrapper may only work if you run it from the same directory.
With SCRIPT_DIR, the wrapper works from anywhere.
| If user runs | $0 may be | dirname -- "$0" gives |
|---|---|---|
| ./linuxcmd | ./linuxcmd | . |
| /usr/local/bin/linuxcmd | /usr/local/bin/linuxcmd | /usr/local/bin |
| ../tools/linuxcmd | ../tools/linuxcmd | ../tools |
$0 tells you how the script was called.
dirname extracts the folder from that path.
cd + pwd converts that folder into an absolute location.
CDPATH= cd -- "$(dirname -- "$0")"
CDPATH is an environment variable that can change how cd searches for directories.
Setting CDPATH= only for this command disables that behavior.
This avoids surprising output or wrong directory resolution on systems where CDPATH is configured.
It is a small detail, but it makes the wrapper more reliable.
dirname -- "$0"
cd -- "some/path"
-- means:
βStop parsing options after this point.β
This protects commands if a filename begins with a dash, such as -test.
If a variable contains a path or user input, quote it.
Use:
"$SCRIPT_DIR"
"$0"
"$@"
| Unquoted | Quoted | Why quoted is safer |
|---|---|---|
| $SCRIPT_DIR | "$SCRIPT_DIR" | Preserves spaces in paths |
| $0 | "$0" | Preserves script path as one argument |
| $@ | "$@" | Preserves each user argument separately |
| $(pwd) | "$(pwd)" | Preserves command output as one string |
"$@"
"$@" means:
Pass every argument exactly as received.
If user types:
linuxcmd previous directory
then "$@" forwards:
"previous" "directory"
| Variable | Meaning |
|---|---|
| $0 | Script name/path |
| $1 | First argument |
| $2 | Second argument |
| $# | Number of arguments |
| $@ | All arguments |
| "$@" | All arguments, safely preserved |
python3 "$SCRIPT_DIR/linux_cmd_tool_v2_1.py" quick "$@"
| Piece | Role |
|---|---|
| python3 | Interpreter for the Python tool |
| "$SCRIPT_DIR/linux_cmd_tool_v2_1.py" | Absolute path to the Python engine |
| quick | Subcommand passed to Python |
| "$@" | All user-provided search words |
User types:
linuxcmd usb mount
Wrapper runs:
python3 /path/to/linux_cmd_tool_v2_1.py quick usb mount
Shell wrapper = convenient command interface
Python script = real logic and data processing
#!/bin/sh
# Wrapper for a local Python tool.
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
python3 "$SCRIPT_DIR/YOUR_TOOL.py" "$@"
Replace YOUR_TOOL.py with your Python script name.
If your Python tool needs a default subcommand, add it before "$@".
python3 "$SCRIPT_DIR/YOUR_TOOL.py" quick "$@"
| Mistake | Example | Fix |
|---|---|---|
| Spaces around = | SCRIPT_DIR = value | SCRIPT_DIR=value |
| Not quoting variables | python3 $SCRIPT_DIR/tool.py | python3 "$SCRIPT_DIR/tool.py" |
| Using $@ unquoted | $@ | "$@" |
| Assuming current directory | python3 tool.py | python3 "$SCRIPT_DIR/tool.py" |
| Using bash syntax in sh | [[ "$x" == yes ]] | Use [ "$x" = yes ] or change shebang to bash |
| No execute permission | ./linuxcmd gives permission denied | chmod +x linuxcmd |
If a shell script fails, first print:
echo "$0"
echo "$SCRIPT_DIR"
echo "$@"
This reveals path and argument problems quickly.
Create hello.sh:
#!/bin/sh
echo "Hello from shell"
Then run:
chmod +x hello.sh
./hello.sh
Create args.sh:
#!/bin/sh
echo "script: $0"
echo "first : $1"
echo "all : $@"
echo "safe : $@"
Then run:
./args.sh previous directory
Create a script that prints its own directory:
#!/bin/sh
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
echo "$SCRIPT_DIR"
Run it from a different directory and confirm the output stays correct.
.bashrc: your interactive shell startup layer
The earlier sections explain individual shell-script ideas. This section connects those ideas to a real workstation:
~/.bashrc is the startup layer Bash reads for an interactive shell. It is not the operating system itself,
and it is not where every tool should be configured. Its job is to make an interactive terminal predictable,
convenient, and aware of the engineering environment you intentionally want available.
Think of .bashrc as a small boot sequence for your terminal:
configure shell behavior β build the executable search path β define selected engineering environment variables
β initialize shell-based tools β load aliases β enable completion.
| Layer | Typical role | Example |
|---|---|---|
| Shell behavior | History, prompt, window handling | shopt -s histappend |
| Executable discovery | Tell Bash where commands may live | PATH |
| Engineering context | Expose selected project/tool roots | PROJECT_HOME, PDK_ROOT |
| Shell-native tool setup | Load tools that must modify the current shell | NVM |
| Convenience layer | Shortcuts for frequent commands/directories | ~/.bash_aliases |
| Interactive assistance | Tab completion | bash-completion |
Examples in this lab are intentionally generic. Use $HOME, placeholder project names,
and non-identifying tool names in shared material. Do not publish personal usernames, real private
workstation paths, employer/customer identifiers, credentials, or proprietary project data.
A good .bashrc should not become a warehouse for every historical path, every application setting,
or any secret. Keep active shell configuration here; keep project logic inside projects; keep credentials in
dedicated credential stores.
case $- in
*i*) ;;
*) return ;;
esac
$- contains Bash mode flags. The flag i means βinteractive.β
If the shell is interactive, continue reading the file. Otherwise, stop.
This prevents terminal-only behavior such as aliases and prompts from leaking into non-interactive scripts.
HISTCONTROL=ignoreboth
shopt -s histappend
HISTSIZE=1000
HISTFILESIZE=2000
| Line | Meaning | Why it exists |
|---|---|---|
HISTCONTROL=ignoreboth | Ignore leading-space commands and immediate duplicates | Cleaner history |
shopt -s histappend | Append rather than overwrite history | Safer with multiple terminals |
HISTSIZE | Commands retained in the current shell | Session memory |
HISTFILESIZE | Commands retained in ~/.bash_history | Persistent memory |
The same control-flow ideas used in shell scriptsβcase, tests, logical operators, variablesβalso
build your interactive environment. .bashrc is therefore a real shell program, just one with a
specific startup purpose.
When you type a command such as muse, Bash usually does not know its absolute filename in advance.
It searches directories listed in PATH, from left to right, and uses the first matching executable.
$HOME/.local/bin:$HOME/bin:/usr/local/bin:/usr/bin:...
Suppose a user-installed CLI tool lives at ~/.local/bin/mytool. An installer can temporarily change its own PATH and run that tool immediately, while the parent terminal still keeps its older environment. Reloading ~/.bashrc makes the updated PATH visible to the current shell.
PATH="$HOME/.local/bin:$PATH"
Your directory is searched first. Use this when your user-installed command should take precedence.
PATH="$PATH:$HOME/some/tool/bin"
Existing system commands keep priority. Use this for secondary engineering tool locations.
path_prepend() {
[ -d "$1" ] || return 0
case ":$PATH:" in
*":$1:"*) ;;
*) PATH="$1:$PATH" ;;
esac
}
export PATH=...
The helper only adds directories that exist and avoids duplicate entries. It turns PATH construction into an explicit policy rather than an accumulation of historical lines.
Directories such as /usr/lib/x86_64-linux-gnu contain shared libraries, not normal commands.
They usually do not belong in PATH. Likewise, Python site-packages is for Python
modules, not shell executables.
[ -d "$HOME/work/my_project" ] && \
export PROJECT_HOME="$HOME/work/my_project"
Define PROJECT_HOME only if the directory really exists. This is better than exporting a path that is invalid on the current machine.
| Variable type | Example | Recommended policy |
|---|---|---|
| Stable user location | $HOME/work | Prefer $HOME over hardcoded usernames |
| Optional project root | PROJECT_HOME | Export only when the directory exists |
| Optional PDK root | PDK_ROOT | Keep conditional and tool-specific |
| Shared/network mount | SHARED_ROOT=/shared/projects | Define only if mounted |
| Python module path | PYTHONPATH | Preserve existing value; avoid global use unless necessary |
| Secret | API token | Do not store directly in .bashrc |
export PYTHONPATH="$TOOL_PY${PYTHONPATH:+:$PYTHONPATH}"
${PYTHONPATH:+:$PYTHONPATH} means: if PYTHONPATH already has a value, append a colon
and that existing value; otherwise append nothing. The new tool path is added without destroying previous state.
source, aliases, and completionexport NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && . "$NVM_DIR/bash_completion"
NVM changes the current shell, especially PATH. A child process cannot permanently change its parent shell.
Therefore . "$NVM_DIR/nvm.sh" (equivalent to source ...) loads NVM into the shell
that you are actually using.
if [ -f "$HOME/.bash_aliases" ]; then
. "$HOME/.bash_aliases"
fi
Separating aliases from .bashrc gives each file one clearer job:
.bashrc defines the environment; .bash_aliases defines your interactive shortcuts.
if ! shopt -oq posix; then
if [ -f /usr/share/bash-completion/bash_completion ]; then
. /usr/share/bash-completion/bash_completion
elif [ -f /etc/bash_completion ]; then
. /etc/bash_completion
fi
fi
Completion is another shell extension loaded into the current Bash process. It teaches Bash how to propose commands, options, branches, filenames, and other context when you press Tab.
.bashrc decision framework
During migration, do not ask only βdoes this line work?β Ask what role the line plays, whether that role is still
active, and whether .bashrc is the correct place for it.
| Question | Decision | Example |
|---|---|---|
| Is this standard interactive-shell behavior? | Usually KEEP | history, prompt, completion |
| Does it make a user-installed executable discoverable? | KEEP if active | ~/.local/bin |
| Is it a real active engineering tool root? | KEEP, preferably conditional | PROJECT_HOME |
| Is it a stale historical path? | REVIEW / archive | old tool tree no longer used |
| Is it project-specific and rarely needed? | Prefer PROJECT-LOCAL setup | special PYTHONPATH |
| Is it duplicated or overridden later? | MERGE / remove duplicate | two definitions of the same alias |
| Is it a secret? | REMOVE from shell startup file | API key / PAT |
Preserve information first. Delete only when the line is clearly wrong, unsafe, redundant, or obsolete. When a better form exists, merge the old intent into the new structure rather than erasing the history of why the line existed.
A practical pattern is to keep an approved dated configuration under ~/projects/dotfiles/bash/, then make ~/.bashrc and ~/.bash_aliases symbolic links to the currently qualified versions. The dated file then serves as both an active configuration and an auditable workstation baseline.
.bashrc
ββ shell behavior
ββ prompt / colors
ββ PATH
ββ engineering environment
ββ NVM / shell-native initialization
ββ ~/.bash_aliases
ββ completion
Click each card to reveal the answer. These preserve the original labβs recall practice.
The original glossary is preserved below as quick reference vocabulary.
The first line like #!/bin/sh that selects the interpreter.
Command interpreter that runs commands and scripts.
Portable shell standard supported on many Unix/Linux systems.
Named string value, e.g. SCRIPT_DIR="/path".
$(command), which runs command and substitutes its output.
Input word passed to a script or command.
Script name/path used to call the script.
All arguments passed to the script.
All arguments safely preserved as separate arguments.
Command that extracts directory portion of a path.
Environment variable affecting cd search behavior.
Small script that calls another tool with a simpler interface.
Bash startup file commonly used to configure interactive shell behavior and environment.
Colon-separated, ordered list of directories Bash searches for executable commands.
Marks a shell variable so programs launched from the shell inherit it.
Execute a shell file inside the current shell process so its environment changes persist.
Interactive shorthand that replaces a command name with another command string.
A named value inherited by child processes when exported, often used to communicate tool or project configuration.
The wrapper gives users a simple command. The shell handles location and arguments. Python performs the deeper logic. This is the core pattern behind many practical engineering tools.