Lecture 8: Arithmetic; Variables
Watch on YouTube →
Overview
Burton Ma explains Bash scripting through exit statuses, special parameters, integer arithmetic, conditionals, random numbers, and variable expansion. Key practical lessons include checking command-line argument counts, sending errors to standard error, and using braces to avoid ambiguous variable names; Bash also treats unset variables as empty strings and nonnumeric arithmetic values as zero.
Key takeaways
- Bash communicates command success through exit statuses: 0 means success, while nonzero values generally indicate failure, and $? retrieves the latest status.
- Script arguments are exposed through $# for the count, $0 for the invocation name, and $1 onward for argument values; parameters numbered 10 or higher require braces.
- Reading an unset Bash variable silently yields an empty string, so misspellings can cause incorrect results without stopping a script.
- Bash evaluates integer arithmetic in (( ... )) or substitutes its result with $(( ... )); nonnumeric values become zero, and arithmetic command status is 1 for a zero result.
- Use >&2 to send diagnostics to standard error and exit 1 to stop a script with a failure status when argument validation fails.
- Braces make variable expansion unambiguous: ${in}_back appends text to a variable, while $in_back attempts to expand a separate variable named in_back.
Chapters
- A Bash script begins with a shebang such as #!/bin/bash on Linux or #!/usr/bin/env bash for locating Bash through the environment.
- The # symbol starts comments except on the first line when it introduces the interpreter directive.
- Bash stores the most recently completed command's exit status in the special parameter $?, with 0 indicating success and nonzero values typically indicating an error.
- Bash comments run from # to the end of a line, and a # inside single or double quotes is not a comment marker.
- Special parameters such as $? and numeric parameters are reserved by Bash and cannot be assigned like ordinary variables.
- The exit status is an integer from 0 to 255, and the meaning of nonzero values depends on the command.
- The example view_args script uses $# to report how many command-line arguments it received.
- $0 contains how the script was invoked, while $1 and $2 contain its first and second arguments.
- Use braces for positional parameters numbered 10 or higher, such as ${10}; without braces, $10 expands as $1 followed by the character 0.
- Unlike Java or Python, Bash does not report an error when a script reads an unset variable; its value expands to an empty string.
- The unset command removes a variable, but reading that variable afterward still produces an empty value rather than an exception.
- A misspelled variable name can therefore let a script continue silently and generate incorrect output.
- Bash evaluates integer expressions inside (( ... )), and arithmetic expansion with $(( ... )) substitutes the calculated value into a command.
- Inside double parentheses, whitespace around operators and assignment signs is allowed, and variable names can be used without dollar signs.
- Bash arithmetic uses integers only; integer width depends on the system and is commonly 64 bits.
- Bash treats nonnumeric text such as ABC as zero inside an arithmetic expression, so ABC + 5 evaluates to 5.
- An unset variable used in arithmetic becomes an empty string, which Bash then treats as zero.
- The (( ... )) arithmetic command returns exit status 1 when its expression evaluates to zero and status 0 when it evaluates to a nonzero value.
- Bash conditionals interpret command exit status 0 as true and nonzero status as false, including the status returned by arithmetic expressions.
- A script can check argument counts with expressions such as (( $# != 1 )) and report errors to standard error using >&2.
- The exit command stops the script and returns a chosen status, for example exit 1 when required arguments are missing.
- The is_even example checks a number's remainder after division by 2; nonnumeric input becomes zero and is consequently treated as even.
- Bash's uppercase RANDOM variable produces a new pseudo-random integer from 0 through 32,767 whenever its value is read.
- For a range from 0 through n - 1, the rand example uses RANDOM % n; for a range from m through n - 1, it scales by n - m and adds m.
- The lecture cautions that Bash RANDOM is a poor choice for security-sensitive randomness and demonstrates checking that rand receives no more than two arguments.
- Bash has no declared variable types: values are generally strings, and numeric interpretation depends on context.
- Assignments use a bare name and an equals sign with no spaces, as in a=2; spaces make Bash try to interpret the left side as a command.
- String concatenation requires no operator: adjacent expansions such as "$a$b" join their values.
- Use $variable or ${variable} to expand a value; a dollar sign does not belong on the left side of an assignment.
- The environment variable USER contains the current account name; "$USER" expands inside double quotes, while '$USER' remains literal.
- Double quotes preserve variable expansion, whereas single quotes suppress the special meaning of the dollar sign.
- Braces delimit a variable name when adjacent text could be mistaken as part of it; in the backup example, ${in}_back correctly appends a suffix.
- Because underscores are legal in variable names, $in_back refers to a different variable than $in followed by _back, and an unset name expands to an empty string.
Transcript excerpt
0:06 Right, good afternoon everybody. Um, so in the previous lecture we were talking about writing a bash script which is just a program written in bash. All right. All right. So, remember the first thing you have to keep in mind is that uh the first line of your script is always going to include the uh interpreter directive hashbang rootbin bash if you're in Linux, right? And this just tells uh your shell that when you run this as a command, you want to use bash um as the interpreter for the rest of the script. If you're on a Mac, you probably want to use the following instead, right? So, hashbang userbin envash that says the same thing just in a wordier way um and in a way such that on
0:55 most of your machines if you set it up properly or according to how the course uh instructions told you you get the proper version of bash to run your program right after that the rest of your script just contains a sequence of bash commands all right so bash is both a shell and a programming language language. So like most other programming languages, Bash has a comment, right? So the comment in Bash is the exact same as in Python. It's just the hash symbol. And so that line right there is a comment, right? The first line is not a comment, right? So if the hash symbol appears on the first line as the first character, it's not a comment. It's the interpreter directive, right? Everywhere else, right? It's a comment. So that's also a
1:42 comment. And so this uh script Looks like it should do nothing, right? And that's what the comment says. It says this program does nothing. Almost, right? And so the almost uh is
This is the start of the transcript. Save this video free for the whole transcript, searchable and time-coded.
Related notes
Summary, takeaways, and chapters were generated by AI from the video's transcript and may contain errors. The video belongs to its creator, Burton Ma.