关于shell:加数字在Shell中的含义

6次阅读

共计 2242 个字符,预计需要花费 6 分钟才能阅读完成。

原文地址

[$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/bash
script="$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:~$ ll
total 44
drwxr-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 h
The script name : ./demo-arges.sh
The first argument :  foo
The second argument : bar
The 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/bash
die(){
    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 here
echo "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/hosts
We 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
}
正文完
 0