Um momento
0x90Lesson 10 of 18

Write your first script

Save commands in a file, store values in variables, quote them correctly, and read arguments and input.

25 min 7-question quiz 2 code exercises
By the end of this lesson you can
  • Create and run a script with a shebang line
  • Set and use variables, and choose between single and double quotes
  • Read command-line arguments ($1, $#, "$@") and input from the user (read)

A script is just a text file of commands. Anything you can type at the prompt can go in a script, and once it’s there you can run it a thousand times without a typo. Here’s a complete one:

1#!/usr/bin/env bash
2# greet.sh - welcome someone aboard
3name="Ada"
4echo "Welcome aboard, $name!"
  • The first line, the shebang (#!), tells the system which interpreter runs the file. #!/usr/bin/env bash finds bash wherever it’s installed.
  • Lines starting with # are comments - notes for humans.
  • Run it with bash greet.sh, or chmod +x greet.sh once and then ./greet.sh.

Variables

Assign with name=value - and no spaces around =. (name = value runs a command called name with the arguments = and value.) Read a variable with $name, or ${name} when letters follow it: "${deck}A".

Every variable is a string; Bash only treats them as numbers inside arithmetic. By convention, your own variables are lower_case and environment variables like HOME and PATH are UPPER_CASE.

variables.sh
1station="Kestrel"
2deck=4
3echo "Station: $station"
4echo "Deck: ${deck}B"
5echo 'Single quotes: $station stays literal'
6echo "Double quotes: $station expands, \$ escapes"
7crew="Ada   Grace"
8echo $crew
9echo "$crew"
Output
Station: Kestrel
Deck: 4B
Single quotes: $station stays literal
Double quotes: Kestrel expands, $ escapes
Ada Grace
Ada   Grace

The last two lines are the most important lesson in shell scripting. Unquoted, $crew is split into words (and each word is checked against filenames), so echo gets two arguments. Quoted, it stays one argument with its spaces intact.

Quotes$var expands?Use for
'single'no - everything is literalfixed text, regexes, awk programs
"double"yes, and $(...) tooalmost every variable use

Arguments

Run ./crew.sh Ada Grace Linus and the script receives three positional parameters:

VariableValue
$0the script’s name, ./crew.sh
$1, $2, $3Ada, Grace, Linus (use ${10} from ten on)
$#how many: 3
"$@"all of them, each as its own word - the one you almost always want
"$*"all of them joined into one string

shift drops $1 and moves everyone down a place. Inside a script, set -- a b c replaces the arguments - the examples here use it to pretend the script was run with arguments.

crew.sh
1set -- Ada "Grace Hopper" Linus    # as if run: ./crew.sh Ada "Grace Hopper" Linus
2echo "$# crew members"
3echo "First: $1"
4for member in "$@"; do echo "- $member"; done
5shift
6echo "After shift: $1 (now $#)"
Output
3 crew members
First: Ada
- Ada
- Grace Hopper
- Linus
After shift: Grace Hopper (now 2)

Reading input

read takes one line from stdin and stores it in variables:

  • read -r name - the whole line goes into name. Always use -r, which stops backslashes being treated as escapes.
  • read -r first rest - the first word goes into first, everything else into rest.
  • read -rp "Name? " name - shows a prompt first (when typing interactively).

In the exercises, “stdin” is the test input, delivered as if someone typed it.

read.sh
1read -r name <<< "Margaret Hamilton"
2read -r first last <<< "Margaret Hamilton"
3read -r cmd args <<< "dock bay 3 now"
4echo "name=[$name] first=[$first] last=[$last]"
5echo "cmd=[$cmd] args=[$args]"
Output
name=[Margaret Hamilton] first=[Margaret] last=[Hamilton]
cmd=[dock] args=[bay 3 now]

Key takeaways

  • Start scripts with #!/usr/bin/env bash; run them with bash file or make them executable.

  • Assign with name=value (no spaces); read with "$name".

  • Single quotes are literal; double quotes expand variables - and quoting prevents word splitting.

  • $1, $# and "$@" hold arguments; read -r reads a line of input.

Lesson quiz

7 questions · pass with 5 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write Bash scripts

Write a script in the editor and run it for real against sample input. Each run gets a fresh Linux sandbox with Bash 5.2 and the GNU tools on Wandbox, a free public service - so experiment freely, even with rm. Your script and test input are sent there.

Exercise 1

Print a crew badge

+25 XP

stdin has two lines: a crew member’s name, then their role. Read both and print:

*** Ada Lovelace - engineer ***
Welcome aboard Kestrel, Ada Lovelace!
  • Ada
  • Grace
script.sh
Loading editor…

Your script runs with Bash 5.2 and GNU tools on Wandbox, a free public service, in a fresh sandbox each time. Your script and test input are sent to that service.

Exercise 2

Roll call

+25 XP

The starter pretends the script was run as ./rollcall.sh Ada "Grace Hopper" Linus. Print:

3 crew: Ada Grace Hopper Linus
Leader: Ada
Others: Grace Hopper Linus (2)

The last line must come from shifting the leader off and then using $@ and $#.

  • Three crew
script.sh
Loading editor…

Your script runs with Bash 5.2 and GNU tools on Wandbox, a free public service, in a fresh sandbox each time. Your script and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: