Learn › Linux Foundations › Multiplexers
Write and run a small Bash program, check its arguments, use a conditional and a loop, and verify real results. Browser practice has no new graded assessment.
You have been giving Bash one command at a time. A shell script saves commands in a text file so Bash can run the same instructions with different inputs. Here you will turn a fixed greeting into a small program that checks its arguments and handles a list of names.
You will use the quoting, redirection, exit status and here documents from Chapters 8 to 17. New ideas are explained before you use them: a script's arguments, its interpreter, executable permission, a conditional and a loop.
The program will greet people whose names you supply. No network, root account or service manager is involved. The script recorder from Chapter 17 and a shell script are different things: the recorder saves terminal output; the program you write here contains instructions.
Practice setup. On a supported desktop, the Linux machine runs in this page as ordinary account admin. It starts a fresh in-memory home disk after each reload or reset. Card progress can survive, but files do not. Recovery blocks below let you rebuild a stage yourself. Copy any code you want to keep before leaving.
This is a new practice edition. Earlier multiplexer records stay with their original lesson. Completing these cards does not pass that older assessment or establish independent mastery.
Consider this two-line file:
#!/bin/bash
printf 'Hello, %s.\n' "$1"
The first line names Bash as the interpreter when the file is executed directly. The next line prints a greeting. The format %s is replaced by one string; \n ends the line. Inside a script, $1 is its first argument. Double quotes keep that value together even when it contains spaces.
Here is a run captured on our browser machine:
bash ~/first-script/hello.sh Ada
Hello, Ada.
Bash reads hello.sh; Ada becomes $1, and printf inserts it into the format. With a quoted two-word argument, the program receives one complete name:
bash ~/first-script/hello.sh 'Ada Lovelace'
Hello, Ada Lovelace.
The quotes group the argument and are removed by the calling shell. The printed name does not include quote marks. The next cards build this example and rehearse both runs before asking you to predict a changed input.
Keep these files in ~/first-script. The -p option lets mkdir succeed when the directory already exists; it does not erase its contents.
prompt: admin@server1:~$ answer: mkdir -p ~/first-script output: hint: Run mkdir -p ~/first-script.
The directory command printed nothing. The next write and read will verify that it can hold your file.
Use the quoted here-document form from Chapter 12. Quoting SCRIPT on the opening line keeps $1 as literal text in the file. An unquoted delimiter would let your current shell expand it too early. The > redirection replaces hello.sh, so use only this named practice path.
Enter the complete block below, line by line. If you returned on a fresh disk, run mkdir -p ~/first-script first. The terminal shows > while it waits for the closing word. Type SCRIPT alone on the last line, without quotes. The opening quotes preserve the dollar expressions for the script to evaluate later.
cat > ~/first-script/hello.sh <<'SCRIPT'
#!/bin/bash
printf 'Hello, %s.\n' "$1"
SCRIPT
prompt: admin@server1:~$ answer: cat > ~/first-script/hello.sh <<'SCRIPT' output: hint: Type the full block above, including the final SCRIPT.
The continuation prompts were your input being echoed, not program output. After the closing word, cat wrote the supplied text into hello.sh.
Before running a new program, inspect what is actually in its file. A command you intended to type is not evidence of the bytes you saved.
Returning after a reload or reset? The saved card is not a saved disk. Recreate this stage by running the block below yourself if its file is missing. These commands replace only the named chapter file. Save any changes you want to keep first. Nothing is replayed automatically.
mkdir -p ~/first-script
cat > ~/first-script/hello.sh <<'SCRIPT'
#!/bin/bash
printf 'Hello, %s.\n' "$1"
SCRIPT
prompt: admin@server1:~$ answer: cat ~/first-script/hello.sh output: #!/bin/bash printf 'Hello, %s.\n' "$1" hint: Use cat ~/first-script/hello.sh.
The saved file still contains "$1". Bash will expand it when the program runs, using that invocation's argument.
Run the script with bash, then the file path, then the name. This explicitly starts Bash and asks it to read your file. It does not require the file's execute bit.
Returning after a reload or reset? The saved card is not a saved disk. Recreate this stage by running the block below yourself if its file is missing. These commands replace only the named chapter file. Save any changes you want to keep first. Nothing is replayed automatically.
mkdir -p ~/first-script
cat > ~/first-script/hello.sh <<'SCRIPT'
#!/bin/bash
printf 'Hello, %s.\n' "$1"
SCRIPT
prompt: admin@server1:~$ answer: bash ~/first-script/hello.sh Ada output: Hello, Ada. hint: Run bash ~/first-script/hello.sh Ada.
The program replaced %s with its first argument, Ada.
Repeat the second worked example. Single quotes around Ada Lovelace keep the words together as one argument at the calling shell. Double quotes around "$1" preserve that grouping inside the script.
Returning after a reload or reset? The saved card is not a saved disk. Recreate this stage by running the block below yourself if its file is missing. These commands replace only the named chapter file. Save any changes you want to keep first. Nothing is replayed automatically.
mkdir -p ~/first-script
cat > ~/first-script/hello.sh <<'SCRIPT'
#!/bin/bash
printf 'Hello, %s.\n' "$1"
SCRIPT
prompt: admin@server1:~$ answer: bash ~/first-script/hello.sh 'Ada Lovelace' output: Hello, Ada Lovelace. hint: Run bash ~/first-script/hello.sh 'Ada Lovelace'.
One argument can contain a space. The program printed the whole name once.
You have run both a one-word argument and a quoted name. Apply the same mechanism to a new input. You can replay either example or use the explanation without a penalty.
>>> The calling quotes make one argument, and "$1" supplies that whole string. Run the changed command yourself and compare the actual result with your prediction.
With bash file, the running Bash program reads a readable file. With a direct path such as ~/first-script/hello.sh, the operating system must permit execution of that file. The first line, #!/bin/bash, then selects its interpreter.
A newly written text file on this image does not have executable permission. A direct attempt therefore fails before the greeting runs. Observe that refusal next. If you already made this file executable on an earlier visit to the card, chmod u-x ~/first-script/hello.sh removes only your owner's execute bit so you can rehearse the refusal again.
Returning after a reload or reset? The saved card is not a saved disk. Recreate this stage by running the block below yourself if its file is missing. These commands replace only the named chapter file. Save any changes you want to keep first. Nothing is replayed automatically.
mkdir -p ~/first-script
cat > ~/first-script/hello.sh <<'SCRIPT'
#!/bin/bash
printf 'Hello, %s.\n' "$1"
SCRIPT
prompt: admin@server1:~$ answer: ~/first-script/hello.sh Ada output: bash: /home/admin/first-script/hello.sh: Permission denied hint: Run ~/first-script/hello.sh Ada without putting bash first.
Permission denied is expected here. This invocation returned status 126. It does not mean the Bash syntax is wrong; the same readable file already worked when passed to bash.
File permission bits decide whether its owner, group or other accounts may read, write or execute it. chmod changes those bits. In u+x, u selects the file's owner and +x adds execute permission. You own this practice file, so no privileged account is needed.
The justified change is to let the owner execute this one script. Do not use a broad permission change such as giving everyone every permission.
Returning after a reload or reset? The saved card is not a saved disk. Recreate this stage by running the block below yourself if its file is missing. These commands replace only the named chapter file. Save any changes you want to keep first. Nothing is replayed automatically.
mkdir -p ~/first-script
cat > ~/first-script/hello.sh <<'SCRIPT'
#!/bin/bash
printf 'Hello, %s.\n' "$1"
SCRIPT
prompt: admin@server1:~$ answer: chmod u+x ~/first-script/hello.sh output: hint: Run chmod u+x ~/first-script/hello.sh.
The permission change printed nothing. Verify it before retrying the direct command.
stat -c %a prints permission bits in numeric form. The three positions here are owner, group and others. Read is 4, write is 2 and execute is 1. The sum 7 means all three; 4 means read only. On this image, a new file starts at 644 and adding owner execute changes it to 744.
Returning after a reload or reset? The saved card is not a saved disk. Recreate this stage by running the block below yourself if its file is missing. These commands replace only the named chapter file. Save any changes you want to keep first. Nothing is replayed automatically.
mkdir -p ~/first-script
cat > ~/first-script/hello.sh <<'SCRIPT'
#!/bin/bash
printf 'Hello, %s.\n' "$1"
SCRIPT
chmod u+x ~/first-script/hello.sh
prompt: admin@server1:~$ answer: stat -c %a ~/first-script/hello.sh output: 744 hint: Run stat -c %a ~/first-script/hello.sh.
744 gives the owner read, write and execute, while the group and other accounts have read only. These are this fixture's permission bits, not a universal default for every system.
Retry exactly the command that was refused. Comparing the same request before and after a focused change makes the result easier to explain.
Returning after a reload or reset? The saved card is not a saved disk. Recreate this stage by running the block below yourself if its file is missing. These commands replace only the named chapter file. Save any changes you want to keep first. Nothing is replayed automatically.
mkdir -p ~/first-script
cat > ~/first-script/hello.sh <<'SCRIPT'
#!/bin/bash
printf 'Hello, %s.\n' "$1"
SCRIPT
chmod u+x ~/first-script/hello.sh
prompt: admin@server1:~$ answer: ~/first-script/hello.sh Ada output: Hello, Ada. hint: Run ~/first-script/hello.sh Ada.
The greeting now appears. You changed the owner execute bit, kept the program text, and verified the direct path.
A useful program must say what inputs it needs. Our first version does not check how many arguments it received. With no argument, "$1" expands to an empty string, so the greeting has a hole. Inspect that behavior before changing the code.
Returning after a reload or reset? The saved card is not a saved disk. Recreate this stage by running the block below yourself if its file is missing. These commands replace only the named chapter file. Save any changes you want to keep first. Nothing is replayed automatically.
mkdir -p ~/first-script
cat > ~/first-script/hello.sh <<'SCRIPT'
#!/bin/bash
printf 'Hello, %s.\n' "$1"
SCRIPT
chmod u+x ~/first-script/hello.sh
prompt: admin@server1:~$ answer: ~/first-script/hello.sh output: Hello, . hint: Run ~/first-script/hello.sh with no name after it.
The program printed Hello, . and still returned success. Successful execution does not establish that a program met its intended purpose.
Inside a script, $# is the number of positional arguments. [ is a command that tests a condition; spaces separate its arguments, and its closing ] must be a separate argument. The numeric comparison -ne means not equal.
if [ "$#" -ne 1 ]; then
printf 'Usage: %s NAME\n' "$0" >&2
exit 2
fi
if runs the test and uses its exit status. If the test succeeds, Bash runs the commands between then and fi. Here that means the argument count is not one. $0 supplies the invocation's script name. >&2 sends the usage explanation to standard error. exit 2 ends the script with a nonzero status we chose for bad input.
For exactly one argument the test fails, so Bash skips the usage branch and reaches the greeting below it. These are two paths through one program. A nonzero *test* result is normal control flow, not necessarily an error in the program.
Here are captured runs of the revised file, first with no argument and then with a valid name:
~/first-script/hello.sh; printf "status=%s\n" "$?"
Usage: /home/admin/first-script/hello.sh NAME
status=2
~/first-script/hello.sh 'Grace Hopper'; printf "status=%s\n" "$?"
Hello, Grace Hopper.
status=0
The final printf runs in the calling shell and prints the preceding script's status immediately. The terminal displays standard output and standard error together, so the text alone does not identify which stream carried it. The >&2 in the code explains that choice.
Keep the greeting but add the argument-count check before it. This block replaces hello.sh. On the same existing file, redirection retains its permission bits; if you are rebuilding after a reload, add owner execute permission after the write.
Enter the complete block below, line by line. If you returned on a fresh disk, run mkdir -p ~/first-script first. The terminal shows > while it waits for the closing word. Type SCRIPT alone on the last line, without quotes. The opening quotes preserve the dollar expressions for the script to evaluate later.
cat > ~/first-script/hello.sh <<'SCRIPT'
#!/bin/bash
if [ "$#" -ne 1 ]; then
printf 'Usage: %s NAME\n' "$0" >&2
exit 2
fi
printf 'Hello, %s.\n' "$1"
SCRIPT
prompt: admin@server1:~$ answer: cat > ~/first-script/hello.sh <<'SCRIPT' output: hint: Type the full block, then SCRIPT on its own line.
The file now rejects the wrong argument count before it reaches the greeting. Read it if you want to check the branch again.
bash -n reads commands and checks their Bash syntax without executing them. It is useful after an edit. A syntax pass does not test whether the program does the right thing or handles all inputs.
Returning after a reload or reset? The saved card is not a saved disk. Recreate this stage by running the block below yourself if its file is missing. These commands replace only the named chapter file. Save any changes you want to keep first. Nothing is replayed automatically.
mkdir -p ~/first-script
cat > ~/first-script/hello.sh <<'SCRIPT'
#!/bin/bash
if [ "$#" -ne 1 ]; then
printf 'Usage: %s NAME\n' "$0" >&2
exit 2
fi
printf 'Hello, %s.\n' "$1"
SCRIPT
chmod u+x ~/first-script/hello.sh
prompt: admin@server1:~$ answer: bash -n ~/first-script/hello.sh output: hint: Run bash -n ~/first-script/hello.sh.
No diagnostic and status 0 mean Bash accepted the syntax. The next two runs test the behavior the syntax check cannot establish.
Run without a name, then print the script's status immediately on the same line. The semicolon allows the status-reporting command to run after failure too.
Returning after a reload or reset? The saved card is not a saved disk. Recreate this stage by running the block below yourself if its file is missing. These commands replace only the named chapter file. Save any changes you want to keep first. Nothing is replayed automatically.
mkdir -p ~/first-script
cat > ~/first-script/hello.sh <<'SCRIPT'
#!/bin/bash
if [ "$#" -ne 1 ]; then
printf 'Usage: %s NAME\n' "$0" >&2
exit 2
fi
printf 'Hello, %s.\n' "$1"
SCRIPT
chmod u+x ~/first-script/hello.sh
prompt: admin@server1:~$ answer: ~/first-script/hello.sh; printf "status=%s\n" "$?" output: Usage: /home/admin/first-script/hello.sh NAME status=2 hint: Run ~/first-script/hello.sh; printf "status=%s\n" "$?".
The usage line identifies the required input; status=2 confirms the chosen failure result. No greeting was printed.
Now supply one quoted name and keep the same status check. A change is not verified by testing only the case you expected to fail.
Returning after a reload or reset? The saved card is not a saved disk. Recreate this stage by running the block below yourself if its file is missing. These commands replace only the named chapter file. Save any changes you want to keep first. Nothing is replayed automatically.
mkdir -p ~/first-script
cat > ~/first-script/hello.sh <<'SCRIPT'
#!/bin/bash
if [ "$#" -ne 1 ]; then
printf 'Usage: %s NAME\n' "$0" >&2
exit 2
fi
printf 'Hello, %s.\n' "$1"
SCRIPT
chmod u+x ~/first-script/hello.sh
prompt: admin@server1:~$ answer: ~/first-script/hello.sh 'Grace Hopper'; printf "status=%s\n" "$?" output: Hello, Grace Hopper. status=0 hint: Run ~/first-script/hello.sh 'Grace Hopper'; printf "status=%s\n" "$?".
The greeting printed once and the script returned 0. The count test skipped the refusal branch.
The branch checks for exactly one argument. Consider a two-word name typed without quotes. You can inspect the code and return to the quoting example before deciding.
>>> Without quotes, the caller supplies two arguments. Two is not one, so the validation branch runs. Try ~/first-script/hello.sh Grace Hopper; printf "status=%s\n" "$?" and inspect both the message and status.
Return to this problem after a break, or on your next visit. The new requirement is to greet one or more supplied names, each on its own line. The one-name check is now too restrictive.
In Bash, "$@" expands to a separate quoted word for each positional argument. It preserves a two-word name as one item. A loop can use those ite
Practice Chapter 18. Your first shell script in a real Linux terminal at The Linux Camp. Progress is verified automatically as you type commands on the machine.