Is the following `readonly` use POSIX-ly correct?

I defined the following as read-only:

readonly root_command='sudo -s'

later used in my script as in:

exec $root_command

My question is, maybe I am slow or something, but I do not fully understand the POSIX man page, as for example if I can single quote or have to double quote and similarly what the -p option is for?

Thank you.

Per POSIX, readonly has two forms:

  1. readonly var, which marks the shell variable var as read-only, and can optionally assign a value to var simultaneously (readonly var=value).

  2. readonly -p, which outputs the names and values of all read-only variables.

They are never combined; you either use -p to see all current read-only variables, or you use readonly to mark a variable as read-only (without -p).

When you mark a variable as read-only, you can also give it a value (which will be its value for good, since it can’t be changed afterwards). This is the same as any variable assignment, and since it takes the form var=value, where value is a word, you need to quote as appropriate, with the same rules as usual (single quotes to prevent variable expansion, double quotes to allow it, etc.).

Note that exec $root_command depends on the current value of $IFS, and it’s better to use functions rather than variables to store commands.

Answered By: Stephen Kitt