Automate command-line steps with careful quoting, arguments and loops.

Before starting: Basic variables and quoted strings.

Practice project: Extend the examples into a small Bash study demo. Explain the setup, one normal case and one failure or boundary case.

Start here: concepts and guided practice

  1. Quote a Bash variable correctly

    Bash is a shell and command language used to automate command-line tasks. Double quotes preserve the space in this variable as one argument. Printf separates its fixed format from the value; do not use untrusted text as a command or format string.

    GNU Bash; save as greet.sh and run bash greet.sh

    name="Student Learner"
    printf 'Hello, %s!\n' "$name"
    Check the output
    Hello, Student Learner!

    Use a two-word name and preserve the quotes.

  2. Bash: visit names containing spaces

    A for loop assigns one value at a time. Quoting both literal names and variable expansion preserves each full name as one argument.

    GNU Bash; save as study.sh and run bash study.sh.

    for name in "Asha Rao" "Ben Li"; do
      printf 'Hello, %s!\n' "$name"
    done
    Check the output
    Hello, Asha Rao!
    Hello, Ben Li!

    Add a third name containing a space.

  3. Bash: supply a default argument

    The :- expansion supplies a default when a parameter is unset or empty. This example prints a greeting without evaluating the input as a command.

    GNU Bash; save as study.sh and run bash study.sh.

    name=${1:-Learner}
    printf 'Hello, %s!\n' "$name"
    Check the output
    With no arguments: Hello, Learner!
    With bash study.sh "Asha Rao": Hello, Asha Rao!

    Compare no argument, an empty argument, and a two-word argument.

Open the Bash learning path on DevStudyHub · Play coding games on this blog

logoblog

No comments:

Post a Comment

Please do not enter any spam link in the comment box.