通过bash脚本传递参数为/ bin / bash的 [英] Passing arguments to /bin/bash via a bash script

查看:343
本文介绍了通过bash脚本传递参数为/ bin / bash的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个bash脚本,通过登录shell取得了一些命令行参数(可能包括空格),并把他们都一个程序(如/ bin / some_program)。这是从bash脚本调用的登录shell将取决于用户的登录shell。让我们假设用户使用/斌/ bash作为在这个例子中登录shell ...但它可能是/斌/ tcsh的或其他任何东西。

如果我知道有多少参数将被传递给some_program,我可以把下面几行,我bash脚本:

 #!/斌/庆典
#...(某​​些行,我们确定该用户的登录shell是bash)...
/斌/ bash的--login -c/斌/ some_program \\$ 1 \\\\$ 2 \\

,然后调用上面的脚本如下:

  my_script这太酷

通过上面的例子我可以证实,some_program接收两个参数,这太和酷。

我的问题是...如果我不知道有多少参数将被传递做什么呢?我想通过所有已发送到一起some_program my_script的参数。问题是我无法弄清楚如何做到这一点。这里有一些事情的不工作的:

  /斌/ bash的--login -c/斌/ some_program $ @# - > 3个参数:这,是,过于
/斌/ bash的--login -c /斌/ some_program$ @# - >通过无参数


解决方案

引用bash的手册 -c


  

如果有-c选项present,那么命令将从字符串读取。如果字符串后还有争论,他们被分配到位置参数,以$ 0起始


对我的作品:

  $猫x.sh
#!/斌/庆典
/斌/ bash的--login -c'回声1:$ 1 2:$ 2 3:$ 3回响$ @
$ ./x.sh富巴,巴兹哎呀blargh quargh
1:富巴2:3巴兹:哎呀blargh quargh

我不知道你是怎么到达通过无参数的结论,也许你错过了 $ 1,0 位?

I am writing a bash script that takes a number of command line arguments (possibly including spaces) and passes all of them to a program (/bin/some_program) via a login shell. The login shell that is called from the bash script will depend on the user's login shell. Let's suppose the user uses /bin/bash as their login shell in this example... but it might be /bin/tcsh or anything else.

If I know how many arguments will be passed to some_program, I can put the following lines in my bash script:

#!/bin/bash
# ... (some lines where we determine that the user's login shell is bash) ...
/bin/bash --login -c "/bin/some_program \"$1\" \"$2\""

and then call the above script as follows:

my_script "this is too" cool

With the above example I can confirm that some_program receives two arguments, "this is too" and "cool".

My question is... what if I don't know how many arguments will be passed? I'd like to pass all the arguments that were sent to my_script along to some_program. The problem is I can't figure out how to do this. Here are some things that don't work:

/bin/bash --login -c "/bin/some_program $@"     # --> 3 arguments: "this","is","too"
/bin/bash --login -c /bin/some_program "$@"     # --> passes no arguments

解决方案

Quoting the bash manual for -c:

If the -c option is present, then commands are read from string. If there are arguments after the string, they are assigned to the positional parameters, starting with $0.

Works for me:

$ cat x.sh
#!/bin/bash
/bin/bash --login -c 'echo 1:$1 2:$2 3:$3' echo "$@"
$ ./x.sh "foo bar" "baz" "argh blargh quargh"
1:foo bar 2:baz 3:argh blargh quargh

I don't know how you arrived at the "passes no arguments" conclusion, maybe you missed the $0 bit?

这篇关于通过bash脚本传递参数为/ bin / bash的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆