Skip to content
shellhacks.dev
Shell Scripting

Replace an array with positional parameters

POSIX sh has no arrays, but set -- a b c turns the positional parameters into one, and "$@" expands each element as its own word without splitting.

1 min read
Summarize in AI

A POSIX shell script needs a list of items that may contain spaces, and there is no array type to hold it.

Shell
set -- "one two" three "four five"
printf '[%s]\n' "$@"
echo "count: $#"
set -- "$@" six
echo "after append: $#"
Text
[one two]
[three]
[four five]
count: 3
after append: 4

set -- replaces the positional parameters, and "$@" expands to one word per parameter with the original boundaries kept. That makes it the only quoting-safe list in a shell without arrays. The rules are in the special parameters section of POSIX. Appending is the same idea: set the parameters to the old ones plus the new value.

The list is the script's own arguments, so it is overwritten for the whole script, and a function gets a separate copy only while it runs. If you need two lists at once, save one in a function call or in a file. Bash and ksh have real arrays and should use them.

Share

More snippets

Shell Scripting

Test for a prefix without double brackets

Test for a prefix in POSIX sh with a case pattern such as release-*), which works in dash and every other shell where double brackets are a syntax error.

1 min read
Shell Scripting

Check if a command exists in POSIX sh

Check that a command exists with command -v in POSIX sh. It is a builtin, it sees functions and builtins, and which does not.

1 min read
Shell Scripting

Get a substring in POSIX sh

POSIX sh has no ${v:2:3}. Build a substring from two prefix strips instead, or use cut when a subprocess is acceptable. Both run in dash.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.