Shell Scripting: Writing and Running Bash Scripts

A shell script is a text file of commands that Bash runs in order, exactly as if you had typed them at the prompt. Scripts turn a sequence you repeat, such as compiling a project, backing up a folder or cleaning log files, into one command you can rerun, share and keep under version control. This lesson covers how a script is organized, how the operating system decides to run it, and how a script receives arguments and reports success or failure. Decisions and loops inside scripts are a separate topic.

Anatomy of a script


Shell
#!/bin/bash
# backup.sh - copy one folder into another
src="$1"
dest="$2"
echo "Copying $src to $dest"
cp -r "$src" "$dest"


The first line is the shebang: the characters #! followed by the absolute path of the interpreter that should run the file. When you execute the file directly, the kernel reads this line and starts /bin/bash with the script's path as its argument. Many authors write #!/usr/bin/env bash instead, which finds Bash through the PATH; this helps on systems where Bash is not in /bin. Every other line beginning with # is a comment.


A variable assignment is written name=value with no spaces around the equals sign; writing src = x makes Bash try to run a command called src. You read a variable by prefixing a dollar sign, as in $src, and you wrap expansions in double quotes so that a value containing spaces stays one word.

Making a script runnable

A newly created file usually has the permissions rw-r--r--, so typing ./backup.sh fails with Permission denied. Each group of three permission letters, for the owner, the group and everyone else, is one octal digit:


digit=4r+2w+1x,r,w,x∈{0,1}\text{digit} = 4r + 2w + 1x, \qquad r, w, x \in \{0, 1\}


Example: the mode rw-r--r-- is 6, 4 and 4, or 644. Running chmod u+x backup.sh adds execute permission for the owner only, giving rwxr--r--, or 744, while chmod 755 backup.sh also lets the group and others run it.


There are three common ways to start a script, and they differ in which process runs it.


Command

Needs execute permission

Uses the shebang

Runs in

./backup.sh a b

Yes

Yes

A new child process

bash backup.sh a b

No, read is enough

No, bash is named explicitly

A new child process

source backup.sh a b

No, read is enough

No

Your current shell


The ./ gives an explicit path. For an external command name without a slash, Bash searches PATH, which usually excludes the current directory. Including the current directory in PATH permits command lookup there; otherwise, give a path or place the script in a directory already listed in PATH.


Executing a script starts a child process. Anything the script changes in its own state, such as the working directory after cd or the variables it sets, disappears when it exits. Sourcing runs the same lines inside your current shell, so those changes persist; that is how files such as ~/.bashrc configure your session.


Two panels compare executing a script in a child process with sourcing it in the current shell.



Arguments and exit status

Words typed after the script name become positional parameters: $1 is the first argument, $2 the second, and so on, while $0 holds the name the script was invoked with. Quoting at the call site decides where one argument ends, so ./backup.sh "My Docs" /tmp passes exactly two arguments.


Parameter

Meaning

Value for ./backup.sh "My Docs" /tmp

$0

Name used to run the script

./backup.sh

$1 and $2

First and second arguments

My Docs and /tmp

$#

Number of arguments

2

"$@"

All arguments, each kept as a separate word

My Docs, then /tmp

$?

Exit status of the most recent command

0 after a successful copy


The built-in shift discards $1 and moves every other argument down one place, reducing $# by one. Scripts use it to peel off a leading destination or option before handling the remaining arguments together.


Every command ends with an exit status, an integer from 0 to 255 where 0 means success and any nonzero value means failure. A script's status is that of the last command it ran, unless it calls exit with a number. The caller reads the status from $? immediately afterwards, because the next command overwrites it.



What to remember

  • The shebang on line 1 names the interpreter used when the file is executed directly.
  • Assign with name=value and no spaces; read with $name inside double quotes.
  • chmod u+x or an octal mode such as 755 makes a script executable; each octal digit is 4r + 2w + 1x.
  • Executing runs a child process, while sourcing runs in the current shell, so cd and variables persist.
  • $1, $#, "$@" and shift handle arguments; $? holds the last exit status, with 0 meaning success.

Example: Passing files to an archiving script

A teaching assistant keeps the following script, archive.sh, in their working directory:


Shell
#!/bin/bash
# archive.sh - copy files into a destination folder
dest="$1"
shift
echo "Destination: $dest"
echo "Files to copy: $#"
mkdir -p "$dest"
cp "$@" "$dest"


They type these commands in the same directory:


Shell
ls -l archive.sh
./archive.sh week5 notes.txt "lab report.pdf" data.csv


a) The listing shows the mode rw-r--r--, and the second command fails with Permission denied. Explain why, give the octal mode of the file, and give the octal mode after running chmod u+x archive.sh.


Typing ./archive.sh asks the kernel to execute the file, which requires the execute bit for the user running it. The owner's triple is rw-, with no x, so the kernel refuses before Bash ever reads the shebang.


Convert each triple with 4r + 2w + 1x. The owner digit is 4 + 2 + 0 = ________, and the group and others triples, r-- each, are ________ apiece, so the current mode is 644.


The command chmod u+x sets only the owner's execute bit, so the owner triple becomes rwx = 4 + 2 + 1 = 7. The new mode is rwxr--r--, or 744.


b) After the permission fix, the same command runs. What do the two echo lines print?


Bash splits the command line into words while honouring the quotes, so the script starts with ________ arguments: week5, notes.txt, lab report.pdf and data.csv. The assignment copies $1, which is ________, into dest.


The shift then discards week5 and renumbers the rest, so $1 becomes ________ and $# drops from 4 to 3. The script prints Destination: week5 followed by Files to copy: 3.


c) Suppose the last line had been written with $@ unquoted. How many source arguments would cp receive, and why does that break the copy?


Unquoted, $@ expands to the three remaining arguments and then splits each one again at spaces. The names notes.txt and data.csv stay single words, but lab report.pdf splits into ________ words, lab and report.pdf.


So cp receives 1 + 2 + 1 = 4 source arguments instead of 3, followed by the destination. It attempts to copy the unintended filenames lab and report.pdf instead of the intended file lab report.pdf. If those unintended files do not exist, cp reports errors for them; if they do exist, it attempts to copy the wrong files. With the quoted form "$@", each original argument stays one word, so cp receives the three intended source filenames.


d) Back with the correct script, lab report.pdf has been deleted before the run. The cp command prints an error for that file but still copies the other two. Assume this cp implementation returns status 1 for this error. The user then types echo $? at the prompt immediately after the script finishes. What does it print, and why?


The script never calls exit, so its exit status is the status of the last command it runs, which is ________. Under the stated assumption, cp returns status 1 for this error even though it copied the other files, and that becomes the script's status. Bash inherits this value; it does not prescribe cp's exact failure code. The general guarantee is a nonzero status on failure.


The parent shell stores the script's status in $?, and echo reads it before any other command overwrites it, so the output is 1, signalling failure to any caller that checks it.

When a Bash command finishes, it returns an exit status that the shell stores in the special parameter $?. By convention, a status of means the command succeeded, and the largest status a command can report is .

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A developer is setting permissions on four shell scripts in a shared project. For each symbolic mode shown by ls -l, enter the equivalent three-digit octal mode for chmod, and answer yes or no to whether an ordinary non-owner member of the file's group can start the script by typing its path, such as ./build.sh. Assume file access is determined solely by the ordinary permission bits shown and all other requirements for running each script are satisfied.

ScriptSymbolic modeOctal modeGroup can execute
build.shrwxr-xr-x
deploy.shrwxr-x---
notes.shrw-rw-r--
secret.shrwx------

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

The executable script tally.sh contains the following lines:


Shell
#!/bin/bash
shift
echo "$#"


It is run with this command:


Shell
./tally.sh "red green" blue "" yellow


What number does the script print? Give your answer as a whole number.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors