>_ IzzyLab

Hands-on task

This task is step 3 of the course “Clean scripts: shellcheck”

Quote the variable

medium~5 min

The script /root/backup.sh copies the file passed as its first argument into /tmp/bk/, but shellcheck complains about an unquoted variable (because of which the script breaks on names with spaces). Fix it so that shellcheck produces no warnings and the script correctly copies even a file with a space in its name. Open the script in the Editor tab above the terminal, and run shellcheck in the terminal.

What you'll practise:
  • shellcheck
  • SC2086
  • word splitting
  • quoting
  • cp

Topic breakdown

Warning SC2086 is about the most common mistake in shell: an unquoted expansion $var undergoes word splitting and glob expansion, so a value with a space scatters into several arguments, and the characters */? get replaced with filenames. The protection is to wrap the expansion in double quotes: inside them the value stays a single argument, but the variable still expands. You don't need to change the script's logic — just make the argument itself safe.

What's checked

  1. shellcheck without warnings
  2. script works with spaces in the name

What it looks like