Batch Files and Scripts, Explained

UPI Study › Courses › Introduction to Operating Systems › Free lessons › Lesson 1.8 Free with a free account

Batch Files and Scripts

Introduction to Operating Systems · Chapter 1: Operating System FoundationsSection 1.8 · lesson 8 of 836 min · free with a free account

← The Command LineNext lesson: The Boot Process →

A free account plays all of Chapter 1 and 3 more lessons of Introduction to Operating Systems. Create a free account →

Earn 3 college credits for Introduction to Operating SystemsRecommended for credit by NCCRS · Computer Science 354 · self-paced · one payment, lifetime access

In this lesson

Writing repeated command routines as Windows batch files and shell scripts.

  • Define a batch file and a shell script and where each one runs
  • Read the remarks, arguments, and loops in a simple batch file and bash script
  • Predict what a script prints when one of its commands fails
  • Explain why a script should be read and tested before it runs

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (931 words). Read along, or search it.

Opening Question

Five Closing Steps, Never Skipped

Sam runs a small online bakery, and every evening he closes the shop the same way. Make a backup folder. Copy the day's orders into it. Copy the price list. Check the backup. Say good night. Five steps. And on a tired Friday, Sam skips one. A computer never gets tired, and never skips a step. Write the steps down once, in a text file, and it repeats them perfectly every time you ask.

Definition

A Text File of Commands in Order

In the last lesson, you typed commands one at a time. Suppose you typed the same ten commands every day. A batch file is a plain text file that lists commands, one per line, so the shell can carry them out in order, like a recipe for the computer. The word batch comes from lesson 1.3: run a whole list of jobs, with no one at the keyboard. The same idea has two common names. On Windows, it's a batch file, ending in dot bat, run by the command prompt. On Linux and macOS, it's a shell script, usually ending in dot s h, run by a shell such as bash. The commands differ. The idea doesn't.

Windows Example

Reading the Windows Closing Routine

Here's Sam's closing routine as a Windows batch file. It can't run here, because this is a Mac, so let's read it together. At-sign echo off stops Windows from printing each command before it runs it. rem starts a remark: a note for people, which the shell skips. Percent one holds the first word typed after the file's name. If Sam types close shop dot bat Tuesday, this line prints: Closing the shop for Tuesday. mkdir backup makes the folder. The for line repeats the lines in brackets once for each file in the list, and percent percent f is the file being handled right now. copy puts it in backup, and greater-than nul throws away copy's own message. Then echo says Saved, with the file's name. dir slash b lists the backup folder as a bare list of names, and the last line says good night.

Shell Script

The Same Routine in Bash

On Linux and macOS, the same routine is a shell script, and this one really runs. Here it is, typed out. The first line, hash bang slash bin slash bash, tells the system which program should run the file. After that, everything following a hash sign is a remark. Dollar one is the first argument: the word typed after the script's name. mkdir dash p makes backup, and doesn't complain if it's already there. The loop runs once per file name. The variable file holds the current name, cp copies it into backup, and echo reports it. Then ls backup shows what arrived, and the last echo says good night.

Running It

Closing the Shop for Tuesday

Sam's folder needs two small files first. Echo puts two dozen muffins into orders, and muffin, three dollars, into prices. Now run it: bash close shop dot s h, Tuesday. Typing bash first means the file needs no permission to run on its own. Lesson 6.7 covers that. Closing the shop for Tuesday. Saved orders, saved prices, the two names in backup, and good night. It's the same routine the batch file runs on Windows, step for step. Only the commands are spelled differently.

Quick Check

A Missing Menu File

Quick check. Sam adds menu dot t x t to the loop's list. But there's no such file in his folder. He runs the script again, for Friday. How many Saved lines does it print? Pause and predict. Three Saved lines, plus an error. cp complained that menu dot t x t doesn't exist, but the script kept going, and the next line printed Saved anyway. A script does exactly what its lines say, not what its name promises. Nothing in this one checks whether a copy worked.

Common Mistake

Running a Script You Have Not Read

That's why the classic mistake is running a script you haven't read. A script can delete files or change settings as fast as it can copy them. So open a downloaded script in a text editor, and read it before you run it. And test your own scripts on copies of your files first.

Where Scripts Shine

Backups, Setups, and Scheduled Jobs

Scripts shine wherever steps repeat: nightly backups, setting up a new computer the same way every time, cleaning out temporary files, or processing a hundred files in a row. They can also start on a schedule, such as every night at midnight, so a job runs while everyone sleeps. Ivy, who looks after the computers at a school, uses a script to prepare each lab machine, so all forty come out identical.

Comparison

Two Files, Same Idea

Sam's laptop runs Windows, so he saved his routine as a dot bat file, with a shortcut on his desktop. Ivy keeps the same routine as a dot s h script on the school's Linux server. Two files, same idea, she told him. You're not learning a command. You're learning to write down what you do, so the computer can do it for you.

Key Takeaways

Commands Written Down Once

To recap. A batch file or shell script is a text file of commands, run in order. Windows uses dot bat files and the command prompt. Linux and macOS use dot s h scripts and a shell like bash. Percent one and dollar one hold the first word typed after the name, and a for loop repeats lines for each item in a list. And a script does exactly what it says, so read it before you run it.

Try It

Planning a Script From a Routine

Here's something to try. Write down, in plain steps, a routine you do on a computer every day, like opening the same three websites. Then mark which steps could each be one command. That list is already the plan for a script.

About Introduction to Operating Systems at UPI Study

Introduction to Operating Systems (Computer Science 354) is a self-paced online course of 83 video lessons in 10 chapters, from what an operating system does and process scheduling to concurrency, memory, devices, file systems, networks, the internet, security and virtual machines. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Linux vs Operating Systems

Why take it here

Why students take Introduction to Operating Systems with UPI Study

What happens under every app you runIntroduction to Operating Systems explains the software that runs a computer: processes and scheduling, threads and synchronization, deadlock, memory and paging, devices and storage, file systems, networking, security and virtualization. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Introduction to Operating Systems carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Batch Files and Scripts

What is the difference between a batch file and a shell script?
A batch file and a shell script are both plain text files of commands run in order, but they belong to different systems. A batch file ends in .bat and runs in the Windows command prompt. A shell script usually ends in .sh and runs in a shell such as bash on Linux or macOS. The command names differ, but the idea is the same.
What does #!/bin/bash mean at the top of a script?
The first line #!/bin/bash, often called a shebang or hash bang, tells the system which program should run the file, here the bash shell. After that line, any text following a hash sign is a remark for people, which the shell skips. Typing bash before the script's name also runs it, even if the file has no permission to run on its own.
How do you pass an argument to a batch file or shell script?
Type the argument after the script's name, and the script reads it through a placeholder. In a Windows batch file, %1 holds the first word typed after the file's name, and in a bash script, $1 does the same job. So running closeshop.bat Tuesday lets a line such as echo Closing the shop for %1 print Closing the shop for Tuesday.
Why does a shell script keep running after a command fails?
A shell script keeps running after a failed command because, by default, it simply carries out each line in turn. If cp fails because a file is missing, the next echo line still prints Saved for that file. To catch failures, the script itself must check them, for example by testing a command's exit status before reporting success.

About the Introduction to Operating Systems course

How many college credits is Introduction to Operating Systems?
Introduction to Operating Systems (Computer Science 354) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Introduction to Operating Systems cost and what is included?
$250, paid once, with lifetime access: all 83 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Introduction to Operating Systems take?
It is self-paced with no deadlines. The 83 lessons total about 10 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Introduction to Operating Systems.

83 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Introduction to Operating Systems
3 credits · NCCRS
Enroll →