Search code examples
bashshellshzsh

Which variable would be $1 in shell?


I created a parametrized shell script. As per my understanding, $0 is the command name, and $1, $2, etc. are all the parameters that follow. So in the statement

ls -lhtr

This would be the corresponding variable count:

ls       $0
-lhtr    $1

I have also learned, that if you don't want to do the following:

chmod +x myScript.sh
./myScipt.sh param1 # in this case, "./myScript.sh" is $0 and "param1" is $1

You can just run

sh myScript.sh param1

However, in the second example, would sh be $0? Or would myScript.sh be $0 (according to the source code in myScript.sh)?

Also, what if I aliased

alias myScript="sh myScript.sh"

?

Would myScript, sh, or myScript.sh be $0?


Solution

  • These variables don't change for every command in the script. When you execute

    sh scriptname foo bar baz
    

    The shell receives the parameters from the operating system. In C, its argv array will look like:

    argv[0] = "sh"
    argv[1] = "scriptname"
    argv[2] = "foo"
    argv[3] = "bar"
    argv[4] = "baz"
    

    It then creates shell variables from this. argv[0] isn't put into a shell variable, the rest are put into $0, $1, $2, and so on, so you get:

    $0 = scriptname
    $1 = foo
    $2 = bar
    $3 = baz
    

    The script can update the parameters starting from $1 using the set built-in, and can use the shift built-in to remove parameters from the beginning of the argument list (this is often used in loops that process arguments from left to right).

    When you write a command like

    ls "$1"
    

    it refers to the arguments to the script, not the arguments on that command line.