shell 'bash -'有什么作用?

ax6ht2ek  于 2022-11-16  发布在  Shell
关注(0)|答案(1)|浏览(127)

我最近看到下面这行字:

curl -fsSL https://deb.nodesource.com/setup_17.x | bash -

bashbash -有什么区别?我试着运行这两个变体,它们似乎做了同样的事情。
man bash也未提供答案。

gudnpqoy

gudnpqoy1#

命令相同。
作者可能认为,将-作为参数传递会使bash从stdin读取命令,但无论如何bash都会这样做。
实际上,bash手册页解释了-等效于--并终止了选项处理:

--    A  --  signals the end of options and disables further option
      processing.  Any arguments after the -- are treated as  file‐
      names and arguments.  An argument of - is equivalent to --.

请注意,如果-后面有内容,则行为可能会有所不同。例如:

$ echo "echo foo" > ./-c
$ chmod +x ./-c
$ export PATH=.:"$PATH"
$ bash   -c "echo bar"
bar
$ bash - -c "echo bar"
foo
$

还要注意,不是使用bash -使其成为登录shell的情况,这可以通过向~/.bash_profile添加一些可打印的内容来演示:

$ export HOME=$(mktemp -d)
$ cd
$ echo "echo login shell" > .bash_profile
$ echo "echo hello" | bash
hello
$ echo "echo hello" | bash -
hello
$ echo "echo hello" | bash -l
login shell
hello
$

联机帮助页中“登录shell是参数零的第一个字符为-的shell”的含义是命令名以连字符开头:

$ cat .bash_profile
echo login shell
$ ln -s /bin/bash ./notLoginShell
$ ln -s /bin/bash ./-isLoginShell
$ export PATH=~:"$PATH"
$ echo "echo hello" | notLoginShell
hello
$ echo "echo hello" | -isLoginShell
login shell
hello
$

增编

使用bash -可能是一种传统技术的延续,该技术过去用于防止特定类型的安全漏洞。
POSIX注解:
在支持set-user-ID脚本的系统上,历史陷门会将脚本链接到名称-i

sh -

或通过:

#! usr/bin/sh -

历史系统假设后面没有选项字母。因此,本卷POSIX.1-2017除了使用常规的“--“参数外,还允许单个字母标记选项的结束,因为人们认为旧的做法是如此普遍。
unix-faq说明:
假设脚本名为/etc/setuid_script,以以下内容开头:

#!/bin/sh

现在,让我们看看如果发出以下命令会发生什么:

$ cd /tmp
$ ln /etc/setuid_script -i
$ PATH=.
$ -i

我们知道最后一个命令将被重新排列为:

/bin/sh -i

但是这个命令会给予我们一个交互环境,setuid为脚本的所有者!
幸运的是,通过创建第一行代码,可以很容易地弥补这个安全漏洞:

#!/bin/sh -

-表示选项列表结束:下一个参数-i将作为要从中读取命令的文件名,就像它应该做的那样!

相关问题