(bash)

CIS241

System-Level Programming and Utilities

bash Arguments and Variables

Erik Fredericks, frederer@gvsu.edu
Fall 2025

Based on material provided by Erin Carrier, Austin Ferguson, and Katherine Bowers

CIS241 | Fredericks | F25 | 21-bash-arguments-variables
(calvin and susie)
CIS241 | Fredericks | F25 | 21-bash-arguments-variables

Arguments (positional parameters)

Modify behavior of program!

  • E.g., cat file --> file is an argument!

  • Reference by ${n} - n is the position

    • What was $0 again?
  • $1, $2, 1st and 2nd (respectively) arguments on command line

    • Need braces for 10 or more: ${10}
CIS241 | Fredericks | F25 | 21-bash-arguments-variables

Arguments (more of)

  • $# - total number of arguments
  • $@ - array of arguments
  • $* - string with arguments separated by space

WHY?

CIS241 | Fredericks | F25 | 21-bash-arguments-variables
(tbc)
CIS241 | Fredericks | F25 | 21-bash-arguments-variables

Variables

Assignment:

age=42

filename=erik.txt

message="This is a test"

SPACING IS IMPORTANT
echo "I am $age$ years old

CIS241 | Fredericks | F25 | 21-bash-arguments-variables

Variables

You can use $(cmd) to grab its input

Combining with variables:

num_lines=$(grep "dog" file.txt | wc - l)

CIS241 | Fredericks | F25 | 21-bash-arguments-variables

Single vs. double quotes

Yes it matters!

Single quotes: everything treated literally

Double quotes: expand variables inside

Try:
echo '$message'
echo "$message"

CIS241 | Fredericks | F25 | 21-bash-arguments-variables

MORE

Variables can be accessed like $var or ${var}

  • Disambiguation!
    • age=102 : echo "I am $ageyears" vs. echo "I am ${age}years"
CIS241 | Fredericks | F25 | 21-bash-arguments-variables

Mathematical

top-corner (jake and finn)

top-right (welcome to hell)

What you expect won't work

Want to do 1 + 1?

  • That's $((1+1))
  • $((num1+num2))

Operators available:

  • +, -, /, *, %, ++, --, **

(Can go deeper with bracket expansion or the expr keyword but that way lies pain)

CIS241 | Fredericks | F25 | 21-bash-arguments-variables

command to call program

echo $0 echo $1 echo $1 weeee script: var1=$1 var2=$2 echo "$var1 and $var2"

coming back to it with loops/arrays

expr 5\* 3 bc command echo "sqrt(16)" | bc