-1

What is the difference between $argv[1] and $1?
$argv[1] and $argv[$1], which is correct?

I tried the below codes and obtained the outputs as mentioned below:

1)

#!/bin/bash
echo "The user $1 is logged on to the system on"

Run as: bash logs.sh home

Output: The user home is logged on to the system on

2)

#!/bin/bash
echo "The user $argv[1] is logged on to the system on"

Run as: bash logs.sh home

Output: The user [1] is logged on to the system on

3)

#!/bin/bash
echo "The user $argv[$1] is logged on to the system on"

Run as: bash logs.sh home

Output: The user [home] is logged on to the system on

Please clarify these.

Tsyvarev
  • 60,011
  • 17
  • 110
  • 153
Salini
  • 11
  • 1
  • 2
  • 8
  • Why is this tagged `linux-kernel`? `bash` also runs on other operating systems – Corion Feb 01 '19 at 08:18
  • 3
    There is no variable named `argv` in bash/shell, and your tests just expose that. (In your tests replace `$argv` with an *empty string*, and the results will be consistent). – Tsyvarev Feb 01 '19 at 09:55
  • Possible duplicate of [What are the special dollar sign shell variables?](https://stackoverflow.com/q/5163144/608639) – jww Feb 01 '19 at 10:12

1 Answers1

0

In case of bash, I usually say, play with it:

> echo $argv[1]
[1]
> argv=blabla
> echo $argv[1]
blabla[1]

The token $argv[1] is parsed as $argv and [1]. The $argv is expanded into the variable argv value, and [1] is left as it is. To access an array by the index, use {}, ex. ${argv[1]}. As you can also see, arrays in bash are indexed from zero:

> argv=(1 2 3)
> echo ${argv[1]}
2

The variable argv is no special name for a variable in bash, it has no special meaning and doesn't have any coleration with positional arguments passed to script. To access arguments use $1 to access first argument, $2 to access the second, use "$@" to expand parameters each to separate word, "$*" expands parameters to a single word and $# get's the count of arguments.

The $argv[$1] has also no special meaning at all. As argv variable is not set, the $argv is expanded into nothing. The first parameter to your script is home so $1 expands to home. The [ ] have no special meaning outside ${ ... } braces. The [ and ] are left untouched. So $argv[$1] is expanded like

`$argv` + `[` + `$1` + `]`
`` + `[` + `home + `]`
`[home]`

You can test $1 variables with simple functions:

> f() { echo $# 1:$1 2:$2 3:$3; }
> f home 
1 1:home 2: 3:
> f home kamil salini
3 1:home 2:kamil 3:salini
KamilCuk
  • 120,984
  • 8
  • 59
  • 111