Mini Project: One Setup Script, Three Shells
Every new project starts the same way: make a folder, add src, tests and docs, write a README, a .gitignore and a config file. In this project you automate that chore with a setup script, and you write it three times: as a bash script for Linux and macOS, a batch file for Windows CMD and a PowerShell script for Windows (and anywhere PowerShell 7 runs). All three must produce exactly the same folder and print exactly the same report.
Along the way you'll use most of this course: arguments with defaults, variables, if, functions/subroutines, redirection, exit codes and the cross-platform rules about paths and line endings.
Step 1: The specification
Writing the same tool in three languages only works if you first agree on what it does. Here's the spec:
setup NAME (NAME defaults to "myapp")
NAME/
├── README.md contains: # NAME
├── .gitignore contains: build/
├── config.json contains: {"name": "NAME", "version": "0.1.0"}
├── docs/
├── src/
└── tests/Rules:
- Idempotent: running it twice must not overwrite anything. Items that already exist are reported as
existsand left alone. - Same report on every OS: one line per item, with
/in paths, then a summary line:
Setting up project 'myapp'
created myapp/
created myapp/src/
...
Done: 7 created, 0 already existedStep 2: The building blocks in bash
Two helper functions do all the work: make_dir creates a folder unless it exists, make_file writes a file unless it exists. Each one counts what it did. Let's try them on their own, calling make_dir twice on the same folder:
created=0
existed=0
make_dir() {
if [ -d "$1" ]; then
echo " exists $1/"
existed=$((existed + 1))
else
mkdir -p "$1"
echo " created $1/"
created=$((created + 1))
fi
}
make_dir demo
make_dir demo
make_dir demo/src
echo "created=$created existed=$existed" created demo/
exists demo/
created demo/src/
created=2 existed=1
The second call finds the folder and leaves it alone. That check-before-acting pattern is what makes the whole script safe to re-run.
Step 3: The complete bash version
Now the full script, saved as setup.sh. The playground writes it to disk with a here-document, makes it executable, runs it for a new project and then runs it again to prove that nothing is overwritten:
cat > setup.sh <<'EOF'
#!/usr/bin/env bash
# setup.sh - create a project skeleton (safe to run twice)
name="${1:-myapp}"
created=0
existed=0
make_dir() {
if [ -d "$1" ]; then
echo " exists $1/"; existed=$((existed + 1))
else
mkdir -p "$1"
echo " created $1/"; created=$((created + 1))
fi
}
make_file() { # make_file PATH CONTENT
if [ -f "$1" ]; then
echo " exists $1"; existed=$((existed + 1))
else
printf '%s\n' "$2" > "$1"
echo " created $1"; created=$((created + 1))
fi
}
echo "Setting up project '$name'"
make_dir "$name"
make_dir "$name/src"
make_dir "$name/tests"
make_dir "$name/docs"
make_file "$name/README.md" "# $name"
make_file "$name/.gitignore" "build/"
make_file "$name/config.json" "{\"name\": \"$name\", \"version\": \"0.1.0\"}"
echo "Done: $created created, $existed already existed"
EOF
chmod +x setup.sh
./setup.sh
echo "README.md changed by hand" >> myapp/README.md
echo "=== second run ==="
./setup.sh
echo "=== result ==="
cat myapp/README.md myapp/config.jsonSetting up project 'myapp'
created myapp/
created myapp/src/
created myapp/tests/
created myapp/docs/
created myapp/README.md
created myapp/.gitignore
created myapp/config.json
Done: 7 created, 0 already existed
=== second run ===
Setting up project 'myapp'
exists myapp/
exists myapp/src/
exists myapp/tests/
exists myapp/docs/
exists myapp/README.md
exists myapp/.gitignore
exists myapp/config.json
Done: 0 created, 7 already existed
=== result ===
# myapp
README.md changed by hand
{"name": "myapp", "version": "0.1.0"}
Points to notice:
${1:-myapp}is the first argument, ormyappwhen there is none.- Every
"$name"is quoted, so a project name with spaces still works. printf '%s\n'writes the content exactly, even if it contains%or a leading-, whichechomight misinterpret.- The second run reports
existsseven times, and the line we appended toREADME.mdsurvived.
Step 4: The batch version for CMD
Batch has no functions, but call :label jumps to a subroutine that receives arguments as %1, %2, … and returns with exit /b. Three batch details matter here:
set "name=%~1"strips quotes from the argument; if it's empty the variable is undefined, soif not definedsets the default.- A trailing backslash in
if exist "%~1\"tests for a folder. %shown:\=/%replaces every\with/in the variable, so the report shows the same paths as bash.
The content of config.json contains quotes, which can't be passed safely as a quoted argument, so :make_file reads it from the content variable instead:
@echo off
(
echo @echo off
echo rem setup.bat - create a project skeleton ^(safe to run twice^)
echo setlocal
echo set "name=%%~1"
echo if not defined name set "name=myapp"
echo set created=0
echo set existed=0
echo echo Setting up project '%%name%%'
echo call :make_dir "%%name%%"
echo call :make_dir "%%name%%\src"
echo call :make_dir "%%name%%\tests"
echo call :make_dir "%%name%%\docs"
echo set "content=# %%name%%"
echo call :make_file "%%name%%\README.md"
echo set "content=build/"
echo call :make_file "%%name%%\.gitignore"
echo set "content={"name": "%%name%%", "version": "0.1.0"}"
echo call :make_file "%%name%%\config.json"
echo echo Done: %%created%% created, %%existed%% already existed
echo exit /b 0
echo.
echo :make_dir
echo set "shown=%%~1"
echo set "shown=%%shown:\=/%%"
echo if exist "%%~1\" ^(
echo echo exists %%shown%%/
echo set /a existed+=1
echo ^) else ^(
echo mkdir "%%~1"
echo echo created %%shown%%/
echo set /a created+=1
echo ^)
echo exit /b
echo.
echo :make_file
echo set "shown=%%~1"
echo set "shown=%%shown:\=/%%"
echo if exist "%%~1" ^(
echo echo exists %%shown%%
echo set /a existed+=1
echo ^) else ^(
echo ^>"%%~1" echo %%content%%
echo echo created %%shown%%
echo set /a created+=1
echo ^)
echo exit /b
) > setup.bat
call setup.bat
echo README.md changed by hand>> myapp\README.md
echo === second run ===
call setup.bat
echo === result ===
type myapp\README.md
type myapp\config.jsonSetting up project 'myapp'
created myapp/
created myapp/src/
created myapp/tests/
created myapp/docs/
created myapp/README.md
created myapp/.gitignore
created myapp/config.json
Done: 7 created, 0 already existed
=== second run ===
Setting up project 'myapp'
exists myapp/
exists myapp/src/
exists myapp/tests/
exists myapp/docs/
exists myapp/README.md
exists myapp/.gitignore
exists myapp/config.json
Done: 0 created, 7 already existed
=== result ===
# myapp
README.md changed by hand
{"name": "myapp", "version": "0.1.0"}
The outer part of this playground only writes setup.bat (that's why every % is doubled and the brackets are escaped as ^(), then runs it twice. On your machine you'd type the file directly; it looks like this:
@echo off
rem setup.bat - create a project skeleton (safe to run twice)
setlocal
set "name=%~1"
if not defined name set "name=myapp"
set created=0
set existed=0
echo Setting up project '%name%'
call :make_dir "%name%"
call :make_dir "%name%\src"
call :make_dir "%name%\tests"
call :make_dir "%name%\docs"
set "content=# %name%"
call :make_file "%name%\README.md"
set "content=build/"
call :make_file "%name%\.gitignore"
set "content={"name": "%name%", "version": "0.1.0"}"
call :make_file "%name%\config.json"
echo Done: %created% created, %existed% already existed
exit /b 0
:make_dir
set "shown=%~1"
set "shown=%shown:\=/%"
if exist "%~1\" (
echo exists %shown%/
set /a existed+=1
) else (
mkdir "%~1"
echo created %shown%/
set /a created+=1
)
exit /b
:make_file
set "shown=%~1"
set "shown=%shown:\=/%"
if exist "%~1" (
echo exists %shown%
set /a existed+=1
) else (
>"%~1" echo %content%
echo created %shown%
set /a created+=1
)
exit /b>"%~1" echo %content% puts the redirection first so a content ending in a digit (like version 2) can't be mistaken for a stream number such as 2>. setlocal keeps name, created and the other variables from leaking into the CMD window after the script ends. Run it as setup.bat or setup.bat shop.
Step 5: The PowerShell version
PowerShell gives us real parameters and functions. The counters live in the script scope, so the functions update them with $script:. Test-Path -PathType Container checks for a folder and -PathType Leaf for a file:
@'
# setup.ps1 - create a project skeleton (safe to run twice)
param([string]$Name = 'myapp')
$script:created = 0
$script:existed = 0
function New-ProjectDir([string]$Path) {
if (Test-Path -LiteralPath $Path -PathType Container) {
" exists $Path/"; $script:existed++
} else {
New-Item -ItemType Directory -Path $Path | Out-Null
" created $Path/"; $script:created++
}
}
function New-ProjectFile([string]$Path, [string]$Content) {
if (Test-Path -LiteralPath $Path -PathType Leaf) {
" exists $Path"; $script:existed++
} else {
Set-Content -LiteralPath $Path -Value $Content -Encoding utf8
" created $Path"; $script:created++
}
}
"Setting up project '$Name'"
New-ProjectDir $Name
New-ProjectDir "$Name/src"
New-ProjectDir "$Name/tests"
New-ProjectDir "$Name/docs"
New-ProjectFile "$Name/README.md" "# $Name"
New-ProjectFile "$Name/.gitignore" 'build/'
New-ProjectFile "$Name/config.json" "{`"name`": `"$Name`", `"version`": `"0.1.0`"}"
"Done: $script:created created, $script:existed already existed"
'@ | Set-Content setup.ps1
./setup.ps1
Add-Content myapp/README.md 'README.md changed by hand'
'=== second run ==='
./setup.ps1
'=== result ==='
Get-Content myapp/README.md, myapp/config.jsonSetting up project 'myapp'
created myapp/
created myapp/src/
created myapp/tests/
created myapp/docs/
created myapp/README.md
created myapp/.gitignore
created myapp/config.json
Done: 7 created, 0 already existed
=== second run ===
Setting up project 'myapp'
exists myapp/
exists myapp/src/
exists myapp/tests/
exists myapp/docs/
exists myapp/README.md
exists myapp/.gitignore
exists myapp/config.json
Done: 0 created, 7 already existed
=== result ===
# myapp
README.md changed by hand
{"name": "myapp", "version": "0.1.0"}
Forward slashes in "$Name/src" work on Windows too, so the paths in the report match the other versions without any replacing. Inside a double-quoted string, a backtick escapes a quote: `". On Windows, run it with .\setup.ps1 -Name shop (your execution policy must allow local scripts, see Your First Script on Each OS).
Step 6: macOS — the same .sh in zsh
On a Mac you don't need a fourth version. The bash script uses only portable features, and its shebang #!/usr/bin/env bash picks bash even when your interactive shell is zsh. It even runs when zsh itself interprets it. Here we call it with a project name:
cat > setup.sh <<'EOF'
#!/usr/bin/env bash
name="${1:-myapp}"
created=0
existed=0
make_dir() {
if [ -d "$1" ]; then
echo " exists $1/"; existed=$((existed + 1))
else
mkdir -p "$1"
echo " created $1/"; created=$((created + 1))
fi
}
make_file() {
if [ -f "$1" ]; then
echo " exists $1"; existed=$((existed + 1))
else
printf '%s\n' "$2" > "$1"
echo " created $1"; created=$((created + 1))
fi
}
echo "Setting up project '$name'"
make_dir "$name"
make_dir "$name/src"
make_dir "$name/tests"
make_dir "$name/docs"
make_file "$name/README.md" "# $name"
make_file "$name/.gitignore" "build/"
make_file "$name/config.json" "{\"name\": \"$name\", \"version\": \"0.1.0\"}"
echo "Done: $created created, $existed already existed"
EOF
zsh setup.sh shop
print -l shop/*(/) shop/*(.) shop/.*Setting up project 'shop'
created shop/
created shop/src/
created shop/tests/
created shop/docs/
created shop/README.md
created shop/.gitignore
created shop/config.json
Done: 7 created, 0 already existed
shop/docs
shop/src
shop/tests
shop/README.md
shop/config.json
shop/.gitignore
The last line uses zsh glob qualifiers to list folders (/), then regular files (.), then hidden files: a quick way to check the result.
Step 7: Compare the three
bash (setup.sh) |
batch (setup.bat) |
PowerShell (setup.ps1) |
|
|---|---|---|---|
| Argument with default | ${1:-myapp} |
set "name=%~1" + if not defined |
param([string]$Name = 'myapp') |
| Helper | function | call :label subroutine |
function |
| Folder exists? | [ -d "$1" ] |
if exist "%~1\" |
Test-Path -PathType Container |
| File exists? | [ -f "$1" ] |
if exist "%~1" |
Test-Path -PathType Leaf |
| Write a file | printf '%s\n' "$2" > "$1" |
>"%~1" echo %content% |
Set-Content |
| Counter | $((n + 1)) |
set /a n+=1 |
$script:n++ |
| Make runnable | chmod +x + shebang |
.bat extension |
.ps1 + execution policy |
The folders, file names and report are identical. One invisible difference remains: line endings. bash writes LF, batch writes CRLF, and PowerShell writes the OS's native ending. Git can normalise that for you with a .gitattributes file (see Cross-Platform Scripts). Store the three scripts in the same repository with *.sh text eol=lf and *.bat text eol=crlf, so each one keeps the line endings its shell expects.
Ideas to extend it
- Add a
--gitoption (-Gitswitch in PowerShell) that runsgit initin the new folder, but only if Git is installed (command -v git,where git,Get-Command git -ErrorAction SilentlyContinue). - Exit with code 1 and a message if the name contains characters that are invalid in file names, and check
$?/%ERRORLEVEL%/$LASTEXITCODEfrom the caller. - Add a
src/main.pywith a "hello" program and atests/test_main.py. - Replace all three with one Python script using
pathliband compare the length and readability.
Learn more: Bash Functions, Batch Subroutines, PowerShell Functions.
Test yourself
What makes the setup script safe to run twice?
- It deletes the folder first
- It checks whether each item exists before creating it
- It runs as administrator
- It uses
mkdir -ponly
In batch, what does if exist "%~1\" (with a trailing backslash) test?
- Whether the argument is empty
- Whether a folder with that name exists
- Whether the file is hidden
- Whether the path is absolute
Why do the PowerShell functions write $script:created++ instead of $created++?
$createdis read-only- To update the variable in the script scope instead of creating a local copy
- To make it an environment variable
- It's required by Set-Content