原文地址

[$1 - Linux Bash Shell Scripting Tutorial Wiki (cyberciti.biz)](https://bash.cyberciti.biz/guide/$1)

案例介绍

**$1** is the first command-line argument passed to the shell script. Also, know as Positional parameters. For example, $0, $1, $3, $4 and so on. If you run ./script.sh filename1 dir1, then。

**$1**是传递给shell脚本的**第一个命令行参数**。另外,也被称为**地位参数**。例如,$0、1、3、4等等。

比方如果你运行./script.sh filename1 dir1,那么:

  • $0 is the name of the script itself (script.sh)
  • $1 is the first argument (filename1)
  • $2 is the second argument (dir1)
  • $9 is the ninth argument
  • ${10} is the tenth argument and must be enclosed in brackets after $9.
  • ${11} is the eleventh argument.
  • $0 代表了脚本名称自身,比方这里的script.sh 就是$0的值。
  • $1 代表了跟在脚本前面的第一个参数,$1 = filename1
  • $2 代表跟在脚本前面的第二个参数,$2 = dir1
  • $9 对应的到 $9 代表之后的第九个参数
  • ${10} 是第10个参数,必须在$9之后用括号括起来。
  • ${11} 是第11个参数。

What does $1 mean in Bash? $1 在Bash脚本的含意

Create a shell script named demo-args.sh as follows:

最快的了解形式是理论在Linux上创立一个测试文件,这里咱们命名为 demo-args.sh

通过vim新建一个文件,脚本的内容如下:

xander@xander:~$ vim demo-arges.sh

文件当中增加内容如下:

#!/bin/bashscript="$0"first="$1"second="$2"tenth="${10}"echo "The script name : $script"echo "The first argument :  $first"echo "The second argument : $second"echo "The tenth and eleventh argument : $tenth and ${11}"

xander@xander:~$ lltotal 44drwxr-x--- 4 xander xander 4096 Feb  3 13:12 ./drwxr-xr-x 3 root   root   4096 Jan  8 03:12 ../....-rw-rw-r-- 1 xander xander  225 Feb  3 13:12 demo-arges.sh....

因为新建的文件不具备x(可执行)权限,应用命令chmod +x demo-arges.sh为新建的脚本文件新增可执行权限。

xander@xander:~$ chmod +x demo-arges.sh 

之后运行脚本,咱们传入字母作为参数:

xander@xander:~$ ./demo-arges.sh foo bar one two a b c d e f z f z hThe script name : ./demo-arges.shThe first argument :  fooThe second argument : barThe tenth and eleventh argument : f and z

从后果来看能够验证之前介绍的办法。

$1 in bash functions $1 在函数含意

Create a new script called func-args.sh;

创立一个名为func-args.sh的新脚本。

xander@xander:~$ vim func-args.sh

增加内容如下:

#!/bin/bashdie(){    local m="$1"  # the first arg     local e=$2    # the second arg    echo "$m"     exit $e}# if not enough args displayed, display an error and die[ $# -eq 0 ] && die "Usage: $0 filename" 1# Rest of script goes hereecho "We can start working the script..."
$# -eq 0 这个判断逻辑是如果传参为0的状况。

同样须要增加可执行权限:

xander@xander:~$ chmod +x func-args.sh

咱们不传入任何参数,间接执行脚本,则会进入到如果显示的args不够多,则显示谬误并完结这一步。留神这里的$0并不是脚本的名称。

xander@xander:~$ ./func-args.sh Usage: ./func-args.sh filename

咱们在脚本中传入参数,后果正确执行:

xander@xander:~$ ./func-args.sh /etc/hostsWe can start working the script...

其余例子

fingerprints() {         local file="$1"         while read l; do                 [[ -n $l && ${l###} = $l ]] && ssh-keygen -l -f /dev/stdin <<<$l         done < $file}