What is the meaning of $1 and $2 in shell/sh script

In shell scripts, $1, $2, etc. represent command-line arguments passed to the script. $0 represents the name of the script itself, $1 represents the first parameter, $2 represents the second parameter, and so on. For example, consider the following shell script (example.sh):

#!/bin/sh

echo "脚本名称: $0"
echo "第一个参数: $1"
echo "第二个参数: $2"

If we run the script and pass two parameters like this:

./example.sh 参数1 参数2

The script will output:

脚本名称: ./example.sh
第一个参数: 参数1
第二个参数: 参数2

Additionally, special variables can be used to get more information:

  • $#: Indicates the number of parameters passed to the script.

  • $*Or $@: In shell scripts, both $* and $@ represent all command-line arguments passed to the script. Although they are interchangeable in many cases, they differ in how they handle arguments with spaces. They behave differently when you use them inside double quotes.

    $*: When you use "$*", all parameters will be treated as a single parameter, concatenated with the first character (space by default). This means that if you have multiple arguments with spaces, they will be treated as one.

    $@: When you use "$@", each argument will be processed individually, even if they contain spaces. Each parameter is treated as its own independent entity.

Here's an example of how these two variables behave differently within double quotes:

#!/bin/sh

echo "使用 \$*:"
for arg in "$*"; do
  echo "参数:$arg"
done

echo "使用 \$@:"
for arg in "$@"; do
  echo "参数:$arg"
done

Save as example.sh

./example.sh "参数 1" "参数 2" "参数 3"

The output will be:

使用 $*:
参数:参数 1 参数 2 参数 3
使用 $@:
参数:参数 1
参数:参数 2
参数:参数 3

Guess you like

Origin blog.csdn.net/crazyjinks/article/details/131204200