7

What function exactly is the "keyword" option assigned by the set command on bash shell?

OPTION:

set -o keyword

OR

set -k

A simple example is enough for me to understand.

testter
  • 1,290
  • 2
  • 11
  • 24
  • 2
    `help set` tells you that they are equivalent. – Panki Jan 27 '20 at 13:18
  • 1
    @Panki You misunderstood the question. I didn't ask the difference, I know they both mean the same thing. You dropped points for nothing, I just mentioned both options so that people who would search either way later would find it easy. – testter Jan 27 '20 at 13:54

2 Answers2

8

Usually, to inject an environment variable for a command, you place an assignment to a name before the command like this:

VARIABLE=value bash -c 'echo "$1 $VARIABLE"' bash hello

This runs bash -c 'echo "$VARIABLE"' bash hello and sets VARIABLE to the string value in the environment of that command. The command, in this case will, print hello value (with hello coming from the in-line script's first command line argument, and value coming from the environment variable).

With set -o keyword (or set -k) in bash (this is a non-standard shell option), the assignment is allowed to occur anywhere on the command line:

$ set -k
$ bash -c 'echo "$1 $VARIABLE"' bash hello VARIABLE=value
hello value
$ bash -c 'echo "$1 $VARIABLE"' bash VARIABLE=value hello
hello value
$ bash -c 'echo "$1 $VARIABLE"' VARIABLE=value bash hello
hello value
$ bash -c VARIABLE=value 'echo "$1 $VARIABLE"' bash hello
hello value
$ bash VARIABLE=value -c 'echo "$1 $VARIABLE"' bash hello
hello value

I've never seen this option used "in the wild" and I'm assuming that it's only used sparingly under very specific circumstances, as it radically changes the way commands are parsed.

Kusalananda
  • 320,670
  • 36
  • 633
  • 936
3

From the manual:

-k

All arguments in the form of assignment statements are placed in the environment for a command, not just those that precede the command name.

With some experimentation:

$ bash -c '
    env | grep -e foo -e baz
    for ((i=0; i<=$#; i++)); do echo "$i = ${!i}"; done
' foo=bar baz=qux
0 = foo=bar
1 = baz=qux

The var=val arguments are plain parameters.

But with set -o keyword

$ set -k
$ bash -c '
    env | grep -e foo -e baz
    for ((i=0; i<=$#; i++)); do echo "$i = ${!i}"; done
' foo=bar baz=qux
foo=bar
baz=qux
0 = bash

The var=val arguments are detected, removed from the parameters, and put in the environment.

glenn jackman
  • 84,176
  • 15
  • 116
  • 168