By the end of this lesson you will be able to
- Explain what a shell script is and how it differs from typing commands one by one.
- Create a script file in the practice directory and run it with bash.
- Read a short script containing a variable, a loop and a condition.
- Use a preview mode first: a dry-run option in bash and -WhatIf in PowerShell.
- Compare the Linux and Windows ways of renaming many files.
A shell script is just a text file of commands that the shell runs in order. Instead of typing ten commands every Monday, you save them once and run them with one line. Scripts are the next rung on the automation ladder, and they can change many files in a second, so we will learn them with a safe habit from the first line: every script that changes things must be able to show what it would do before it does it. Everything in this lesson happens only inside your practice folder, with made-up files.
A script is a saved list of commands
Earlier, you typed commands such as ls and mv one at a time and watched each result. A script holds the same commands in a plain text file. When you run it, the shell reads the lines from the top and carries them out in order. Scripts also let you add a few programming ideas you met in the programming lessons: variables, loops and conditions.
- Step 1: Write the commandsPlain text file
- Step 2: Preview runPrints, changes nothing
- Step 3: Read the previewIs it what you meant?
- Step 4: Run for realPractice folder only
- Step 5: Check resultsls or Get-ChildItem
Read this figure as text
A flow from writing a script to previewing, running on a practice folder and checking the results.
Five steps. 1: write the commands into a text file, for example rename.sh. 2: run the script in preview mode, which only prints what it would do. 3: read the preview and compare it with what you expected. 4: run it for real, in the practice folder. 5: check the results with ls on Linux or Get-ChildItem on Windows. If the preview was wrong, go back to step 1 and fix the script.
Set up a practice folder
We will make a folder called auto-demo inside your practice folder, with three empty files named like monthly reports. The script will add the prefix 2025- to each name, so report-jan.txt becomes 2025-report-jan.txt. The files are empty and made up, so nothing can be lost.
Create the practice files
Open Terminal. The first command makes the folder (-p means: make parent folders too, and do not complain if it already exists). The second moves you into it. The third creates three empty files. The last lists them.
mkdir -p ~/practice/auto-demo
cd ~/practice/auto-demo
touch report-jan.txt report-feb.txt report-mar.txt
lsreport-feb.txt report-jan.txt report-mar.txtOpen Start, type PowerShell and open Windows PowerShell or Terminal. The first command makes the folder (-Force means: no error if it exists). The second moves you into it. The third creates three empty files. The last lists them. $HOME means your own user folder, such as C:\Users\Amina.
New-Item -ItemType Directory -Path "$HOME\practice\auto-demo" -Force
Set-Location "$HOME\practice\auto-demo"
New-Item -ItemType File -Path report-jan.txt, report-feb.txt, report-mar.txt
Get-ChildItemYou should see a table listing the three files, with the mode -a----, a modified time, a length of 0 and the file names.
Ubuntu: your first script
We will use nano, a simple text editor that runs inside the terminal. Type nano rename.sh and press Enter. A blank editor opens. Type or paste the script below. To save, press Ctrl+O and then Enter to confirm the file name. To leave, press Ctrl+X.
#!/bin/bash
# rename.sh: add the prefix 2025- to files named report-*.txt
# "bash rename.sh" shows a PREVIEW. "bash rename.sh --go" really renames.
mode="$1"
for f in report-*.txt; do
[ -e "$f" ] || continue
new="2025-$f"
if [ "$mode" = "--go" ]; then
mv -n -- "$f" "$new"
echo "Renamed: $f -> $new"
else
echo "Would rename: $f -> $new"
fi
done
if [ "$mode" != "--go" ]; then
echo "Dry run only. Nothing was changed."
fiRead it line by line before you run anything. The first line, starting #!, names the program that should run the file. Lines starting with # are comments for humans. mode="$1" stores the first word you type after the script name, so --go or nothing. The line for f in report-*.txt; do is a loop: it takes each file whose name starts with report- and ends with .txt, one at a time, calling it f. The line [ -e "$f" ] || continue skips the loop turn if no such file exists. new="2025-$f" builds the new name. The if line chooses between real renaming and printing. In mv -n -- "$f" "$new", -n means do not overwrite an existing file and -- marks the end of options, so odd file names are not mistaken for options.
forStart a loop f VariableHolds one file name each timeinThe list follows report-*.txtPattern* matches any characters; doBody beginsEnds with doneRead this figure as text
The line for f in report-*.txt; do split into labelled parts.
The loop line is for f in report-*.txt; do. The word for starts a loop. The letter f is the variable that holds one file name each time round. The word in introduces the list. The pattern report-*.txt matches every file starting with report- and ending with .txt, because the star stands for any characters. The semicolon and the word do start the body of the loop, which ends later with done.
Preview, then run
Step 1: Create the file
In the practice folder, run
nano rename.sh, enter the script, pressCtrl+O, Enter, thenCtrl+X.You should see: You are back at the prompt.
lsshows rename.sh as well as the three report files.Step 2: Run the preview
Type
bash rename.shand press Enter. Running it withbashmeans you do not need to change any file permissions.You should see: Three lines starting 'Would rename:' and then 'Dry run only. Nothing was changed.' The file names are unchanged.
Step 3: Compare with your plan
Ask yourself: are these the three files I meant, and are the new names right?
You should see: Yes. If not, edit the script and preview again.
Step 4: Run for real
Type
bash rename.sh --goand press Enter.You should see: Three lines starting 'Renamed:'.
Step 5: Check the result
Type
ls.You should see: 2025-report-feb.txt 2025-report-jan.txt 2025-report-mar.txt rename.sh
Step 6: Run it again
Type
bash rename.sh --goonce more.You should see: No 'Renamed' lines. The loop pattern no longer matches, so nothing happens twice. A script that is safe to repeat is a good script.
- Marker 1: Preview: only prints
- Marker 2: --go makes the real change
Read this figure as text
A simulated terminal showing a script preview and then a real run.
A terminal in the folder ~/practice/auto-demo. The learner types bash rename.sh. The output is three lines: Would rename report-feb.txt to 2025-report-feb.txt, the same for report-jan.txt and report-mar.txt, and then the line Dry run only. Nothing was changed. Mark 1 points to the preview lines. The learner then types bash rename.sh --go and the output is three lines starting Renamed. Mark 2 points to the command with the --go flag, which is the only thing that makes real changes.
Windows: the same job in PowerShell
PowerShell has a built-in safety switch. Many commands that change things accept -WhatIf, which means: describe what you would do and do nothing. We use it first. Here Get-ChildItem -Filter "report-*.txt" lists matching files, the brackets collect the list before any renaming begins, the pipe | hands each file to Rename-Item, and -NewName { "2025-" + $_.Name } builds a new name from the file's current name ($_ means the item being handled).
(Get-ChildItem -Filter "report-*.txt") | Rename-Item -NewName { "2025-" + $_.Name } -WhatIfYou should see three lines like the one below, one for each file. Only the first is shown here. Your folder path will show your own user name.
What if: Performing the operation "Rename File" on target "Item: C:\Users\Amina\practice\auto-demo\report-feb.txt Destination: C:\Users\Amina\practice\auto-demo\2025-report-feb.txt".If the preview matches your plan, run the same command without -WhatIf. It prints nothing when it succeeds. Then list the folder to check.
(Get-ChildItem -Filter "report-*.txt") | Rename-Item -NewName { "2025-" + $_.Name }
Get-ChildItem- Script file: rename.sh
- Loop: for f in report-*.txt
- Preview: bash rename.sh
- Real run: bash rename.sh --go
Safety flag written by you.
- Commands joined by a pipe
- Get-ChildItem | Rename-Item
- Preview: add -WhatIf
- Real run: remove -WhatIf
Safety switch built in.
Read this figure as text
A comparison of the Linux bash script and the Windows PowerShell commands.
Two columns. Ubuntu with bash: save a script file rename.sh containing a for loop; preview with bash rename.sh; run for real with bash rename.sh --go; the safety is a --go flag that you wrote yourself. Windows with PowerShell: type a command that pipes Get-ChildItem into Rename-Item; preview with the -WhatIf switch; run for real by removing -WhatIf; the safety switch is built in to many PowerShell commands.
Habits of a careful script writer
- Preview first. Build in a dry run, or use
-WhatIf, before any command that renames, moves or overwrites. - Be specific.
report-*.txtis safer than*, which matches everything. - Do not overwrite. Options such as
mv -nrefuse to replace an existing file. - Work in the practice folder. Check where you are with
pwd(Linux) orGet-Location(Windows) before you run anything. - Avoid deleting. A script that deletes should be written much later, after you have a backup routine. Prefer moving files to a new folder.
- Comment your script. Write one line saying what it does, and how to run it. You will forget in a month.
To clean up, open your file manager, go to the practice folder and move auto-demo to the Trash or Recycle Bin. Doing it with the file manager is deliberate: you can see exactly what you are removing, and you can restore it if you moved the wrong folder.
Common mistakes
✖ Instead of: Using * instead of a specific pattern, so the script touches every file in the folder.
✔ Do this: Use a narrow pattern such as
report-*.txt, and preview to see exactly which files match.✖ Instead of: Running a script you found online without reading it.
✔ Do this: Only run scripts you can read and explain. Test unfamiliar ideas in the practice folder.
✖ Instead of: Running the script from the wrong folder.
✔ Do this: Check your location with
pwdorGet-Locationfirst. The preview shows the file names, which is a good sign you are in the right place.✖ Instead of: Forgetting that a rename could run twice and add the prefix twice.
✔ Do this: Design the pattern or a check so that running again does nothing.
If something goes wrong
bash rename.shsaysNo such file or directory.- You are probably in a different folder, or you saved the script elsewhere. Run
pwdandls, thencd ~/practice/auto-demoand try again. - The preview prints nothing at all.
- No files match the pattern. Check that the three report files exist (
ls) and that their names start withreport-and end with.txt. - PowerShell says
running scripts is disabled on this system. - That message applies to saved .ps1 files. Paste the commands straight into the window as shown, and leave the security setting alone.
- nano shows odd characters or I cannot leave it.
- Press
Ctrl+Xto exit. If it asks whether to save, pressYand then Enter, orNto discard.
Key terms
- Shell script
- A text file of commands that the shell runs in order, so you can repeat a job with one command.
- Dry run
- Running a task in a way that only shows what it would do, without changing anything.
- Loop
- A part of a program that repeats instructions again and again.
- Variable
- A named box in a program that holds a value which can change.
- Condition
- A test in a program that is either true or false and decides what happens next.
Practise it for real
Reading is not the same as being able to do it. Complete these on your own computer, then tick only what you have actually done. These ticks are your own honest record: nothing checks them for you.
Preview and rename the practice files
On your own computer, follow the lesson to create the practice folder and three report files. Create the script (Ubuntu) or type the preview command (Windows). Run the preview and read it, then run the real rename and check the folder. Finally, run the real command a second time and note that nothing changes.
Challenge: a different rule
In a new practice folder, create four empty files named photo-1.txt to photo-4.txt. Write your own script (Ubuntu) or command (Windows) that adds the prefix holiday- to them. It must preview first, must match only files starting with photo-, and must be safe to run twice. Test it, then explain in two sentences how you made sure it could not touch other files.
Knowledge check
6 questions. You need 80% to pass. Mistakes here are part of learning, and you can retry as often as you like.
Summary
- A shell script is a saved list of commands that the shell runs in order.
- Variables, loops and conditions make a script flexible, but also make mistakes repeat.
- Always build a preview into scripts that change files: a --go flag in bash or -WhatIf in PowerShell.
- Match only the files you mean, avoid overwriting, and make the script safe to run twice.
- Only run scripts you understand, and only on practice files while you are learning.
Checklist: can you do these?
Marking a lesson as read does not prove you can do it. Skills count as demonstrated when you pass the quiz (not yet) and complete the practical tasks (not yet).
Related lessons
References and further reading
Official sources for details that can change between versions.
- Bash Reference Manual (GNU Project)
- Rename-Item (Microsoft Learn)
- Ubuntu command line for beginners (Ubuntu)