The Academy

Loading the search index…

Searches the academy on this device only.

Your first simple shell scripts

Write and run a small shell script on Ubuntu, and the matching PowerShell commands on Windows, that renames practice files only after a preview, so you learn automation with a safety net.

35 minintermediateUbuntu/LinuxWindowsPractical task needs a laptop or desktop

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).

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.

Diagram

Write the commands once, preview them, then run them for real.

  1. Step 1: Write the commandsPlain text file
  2. Step 2: Preview runPrints, changes nothing
  3. Step 3: Read the previewIs it what you meant?
  4. Step 4: Run for realPractice folder only
  5. Step 5: Check resultsls or Get-ChildItem
Write the commands once, preview them, then run them for real.
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.

Terminal (Linux) · you can run this on your own computer
mkdir -p ~/practice/auto-demo
cd ~/practice/auto-demo
touch report-jan.txt report-feb.txt report-mar.txt
ls
Text
report-feb.txt  report-jan.txt  report-mar.txt
Expected output

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.

Terminal (Linux)
#!/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."
fi
rename.sh: previews by default, renames only with --go

Read 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.

Diagram

The loop line splits into a keyword, a variable name, a pattern and a marker for the start of the body.

forStart a loop
f VariableHolds one file name each time
inThe list follows
report-*.txtPattern* matches any characters
; doBody beginsEnds with done
The loop line splits into a keyword, a variable name, a pattern and a marker for the start of the body.
Read 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

  1. Step 1: Create the file

    In the practice folder, run nano rename.sh, enter the script, press Ctrl+O, Enter, then Ctrl+X.

    You should see: You are back at the prompt. ls shows rename.sh as well as the three report files.

  2. Step 2: Run the preview

    Type bash rename.sh and press Enter. Running it with bash means 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.

  3. 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.

  4. Step 4: Run for real

    Type bash rename.sh --go and press Enter.

    You should see: Three lines starting 'Renamed:'.

  5. Step 5: Check the result

    Type ls.

    You should see: 2025-report-feb.txt 2025-report-jan.txt 2025-report-mar.txt rename.sh

  6. Step 6: Run it again

    Type bash rename.sh --go once 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.

Simulated interface: not a real screenshot

The preview prints what would happen; the real run changes the files.

Terminal (simulated)
  1. Marker 1: Preview: only prints
  2. Marker 2: --go makes the real change
The preview prints what would happen; the real run changes the files.
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).

PowerShell (Windows) · you can run this on your own computer
(Get-ChildItem -Filter "report-*.txt") | Rename-Item -NewName { "2025-" + $_.Name } -WhatIf
Step 1: preview (changes nothing)

You 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.

Text
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.

PowerShell (Windows) · you can run this on your own computer
(Get-ChildItem -Filter "report-*.txt") | Rename-Item -NewName { "2025-" + $_.Name }
Get-ChildItem
Step 2: the real rename, then check
Diagram

The same safe idea in two shells: preview first, then run.

Ubuntu (bash)
  • 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.

Windows (PowerShell)
  • Commands joined by a pipe
  • Get-ChildItem | Rename-Item
  • Preview: add -WhatIf
  • Real run: remove -WhatIf

Safety switch built in.

The same safe idea in two shells: preview first, then run.
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-*.txt is safer than *, which matches everything.
  • Do not overwrite. Options such as mv -n refuse to replace an existing file.
  • Work in the practice folder. Check where you are with pwd (Linux) or Get-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 pwd or Get-Location first. 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.sh says No such file or directory.
You are probably in a different folder, or you saved the script elsewhere. Run pwd and ls, then cd ~/practice/auto-demo and 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 with report- 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+X to exit. If it asks whether to save, press Y and then Enter, or N to 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.

Guided exerciseNeeds a laptop or desktop

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.

You have succeeded when:
Independent challengeNeeds a laptop or desktop

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.

You have succeeded when:

Knowledge check

6 questions. You need 80% to pass. Mistakes here are part of learning, and you can retry as often as you like.

  1. Question 1.What is a shell script?
  2. Question 2.In PowerShell, adding -WhatIf to Rename-Item renames the files and also shows a report.
  3. Question 3.Wanjiru writes a rename script and wants to test it. She has a folder of 300 real family photos and a practice folder with five made-up files.Where should she first run the script, and how?
  4. Question 4.Match each piece of the bash script to its job.
  5. Question 5.You type ./rename.sh and see 'Permission denied'. What is the simplest explanation?
  6. Question 6.Put the safe script workflow in order.
    1. Write the script in the practice folder
    2. Check the folder to confirm the result
    3. Run the preview and read the output
    4. Run it for real

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.

On this page