Bash – unset the $1 variable

bashsetvariable

Is it possible to unset the $1 variable? If not, I can't find out where it is explained in man.

[root@centos2 ~]# set bon jour
[root@centos2 ~]# echo $1$2
bonjour
[root@centos2 ~]# unset $1
[root@centos2 ~]# echo $1$2
bonjour
[root@centos2 ~]#

EDIT:

Finaly, here is what I found out in man (man set option double-dash) to empty all the positional parameters (and the man used the word "unset"!):

If no arguments follow this option, then the positional parameters
are unset.

[root@centos2 ~]# echo $1

[root@centos2 ~]# set bon jour
[root@centos2 ~]# echo $1$2
bonjour
[root@centos2 ~]# set --
[root@centos2 ~]# echo $1$2

[root@centos2 ~]#

It's @Jeff Schaller's answer that helped me understand that.

Best Answer

You can't unset it, but you may shift $2 into $1:

$ set bon jour
$ echo "$1$2"
bonjour

$ shift
$ echo "$1$2"  # $2 is now empty
jour

shift will shift all positional parameters one step lower. It is common for e.g. command line parsing loops (that does not use getopt/getopts) to shift the positional parameters over in each iteration while repeatedly examining the value of $1. It is uncommon to want to unset a positional parameter.

By the way, unset takes a variable name, not its value, so unset $1 will in effect unset the variable bon (had it been previously set).

Related Question