Skip to content

Files

Latest commit

 

History

History
56 lines (35 loc) · 1.4 KB

SC2206.md

File metadata and controls

56 lines (35 loc) · 1.4 KB

Pattern: Unquoted variable expansion in array

Issue: -

Description

You are expanding unquoted variable in an array. This will invoke the shell's word splitting and glob expansion.

Instead, prefer explicitly splitting (or not splitting):

  • If the variable should become a single array element, quote it.
  • If you want to split into lines or words, use mapfile, read -ra and/or while loops as appropriate.

This prevents the shell from doing unwanted splitting and glob expansion, and therefore avoiding problems with data containing spaces or special characters.

Example of incorrect code:

array=( $var )

Example of correct code:

If the variable should be a single element:

array=( "$var" )

If it's multiple lines, each of which should be an element:

# For bash
mapfile -t array <<< "$var"

# For ksh
printf '%s\n' "$var" | while IFS="" read -r line; do array+=("$line"); done

If it's a line with multiple words (separated by spaces, other delimiters can be chosen with IFS), each of which should be an element:

# For bash
IFS=" " read -r -a array <<< "$var"

# For ksh
IFS=" " read -r -A array <<< "$var"

Exceptions

If you have already taken care (through setting IFS and set -f) to have word splitting work the way you intend, you can ignore this warning.

Further Reading