处理时如何传递+读取参数(管)?

时间:2017-04-27 12:34:54

标签: linux bash macos ubuntu centos

我正在尝试传入参数并将其打印出来。我不能。

尝试#1

curl www.site.com/bash/bashrc.sh | bash

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  3391  100  3391    0     0  66809      0 --:--:-- --:--:-- --:--:-- 67820
There 0 arguments

尝试#2

curl www.site.com/bash/bashrc.sh | bash yellow red green

bash: yellow: No such file or directory
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  3391  100  3391    0     0   130k      0 --:--:-- --:--:-- --:--:--  132k
(23) Failed writing body

我的目标是能够访问我在脚本中传递的参数:yellowredgreen

[0]:bash

[1]:黄色

[2]:红色

[3]:绿色

bashrc.sh

#!/bin/bash

for i in $@
do echo $i
done

echo "There $# arguments"

....

我怎样才能实现这一目标?

1 个答案:

答案 0 :(得分:1)

使用-s开关:

curl www.site.com/bash/bashrc.sh | bash -s yellow red green

yellow
red
green
There 3 arguments

根据man bash

-s  If the -s option is present, or if no arguments remain after option processing,
    then commands are read from the  standard  input. This  option allows the positional
    parameters to be set when invoking an interactive shell.