Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "set - $VARIABLE" mean in bash?

Tags:

bash

shell

Recenly, i read Learning the bash Shell, 3rd Edition in chapter 7 section "Reading user input". When i See the code below,

echo 'Select a directory:'
done=false

while [ $done = false ]; do
        do=true
        num=1
        for direc in $DIR_STACK; do
                echo $num) $direc
                num=$((num+1))
        done
        echo -n 'directory? '
        read REPLY

        if [ $REPLY -lt $num ] && [ $REPLY -gt 0 ]; then
                set - $DIR_STACK

                #statements that manipulate the stack...

                break
        else
                echo 'invalid selection.'
        fi
done

What is the exact meaning of set - $DIR_STACK?

like image 822
Give_me_5_dolloars Avatar asked Sep 07 '25 03:09

Give_me_5_dolloars


1 Answers

This will string-split and glob-expand the contents of $DIR_STACK, putting the first in $1, the second in $2, etc. It's not good practice -- well-written scripts don't rely on string splitting (see the advice at the very top of BashPitfalls, and many of the bugs below are caused by failures to heed that advice).

It's more properly written with --, not -. This is defined by POSIX Utility Syntax Guidelines, entry #10:

The first -- argument that is not an option-argument should be accepted as a delimiter indicating the end of options. Any following arguments should be treated as operands, even if they begin with the - character.


The use of set to change the argument list ($1, $2, etc) is also specified by POSIX, though (again) the standard specifies --, not -:

The remaining arguments [ed: after processing options] shall be assigned in order to the positional parameters. The special parameter # shall be set to reflect the number of positional parameters. All positional parameters shall be unset before any new values are assigned.

The special argument -- immediately following the set command name can be used to delimit the arguments if the first argument begins with + or -, or to prevent inadvertent listing of all shell variables when there are no arguments. The command set -- without argument shall unset all positional parameters and set the special parameter # to zero.

like image 179
Charles Duffy Avatar answered Sep 09 '25 02:09

Charles Duffy