如何获取命令行参数?

时间:2021-05-04 00:38:45

suppose I am passing a command line parameters to my shell script as follows :

假设我将命令行参数传递给我的shell脚本,如下所示:

ex 1 ) ./myshell_script a b c d e f

ex 1)./myshell_script a b c d e f

ex 2 ) ./myshellscript f d e b c a

ex 2)./myshellscript f d e b c a

My question is that , If I want to get the parameter "c" that is always after parameter "b" [ since the command line parameters may be provided in any order ] , How I can get the value that is always after parameter "b" ?

我的问题是,如果我想获取始终在参数“b”之后的参数“c”[因为命令行参数可以按任何顺序提供],我如何获得始终在参数“b之后的值” “?

3 个解决方案

#1


1  

$ ./a.sh f d e b c a
c

code

#!/bin/bash

i=
for p in $@; do

    if [ "$i" == "1" ];then
        echo $p
        exit
    fi
    if [ "$p" == "b" ];then
        i=1
    fi

done

#2


0  

Using getopts

It's good practice not to rely on parameters orders, but instead assign them to unambiguous values using getopts. This allow you to write things as ./myshell_script -a a -b b -c c -d d -d e -f f which is equivalent to any permutation of it ./myshellscript -f f -d d -e e -b b -c c -a a.

最好不要依赖参数命令,而是使用getopts将它们分配给明确的值。这允许你把东西写成./myshell_script -a a -b b -c c -d d -d e -f f,它相当于它的任何排列./myshellscript -f f -d d -e e -b b -c c -a a。

Not having to worry about order is well worth the couple of extra lines at the beginning of the script and extra characters in its call.

不必担心订单是值得在脚本开头的几行额外的行和其调用中的额外字符。

Getopts Tutorial on Bask-hackers

关于Bask-hackers的Getopts教程

#3


0  

myshellscript

myshellscript

#!/bin/bash
grep -oP 'b\s*\K[^ ]+' <<<$*

Test:

测试:

% myshellscript a b c d e f
c
% myshellscript f d e b c a
c

#1


1  

$ ./a.sh f d e b c a
c

code

#!/bin/bash

i=
for p in $@; do

    if [ "$i" == "1" ];then
        echo $p
        exit
    fi
    if [ "$p" == "b" ];then
        i=1
    fi

done

#2


0  

Using getopts

It's good practice not to rely on parameters orders, but instead assign them to unambiguous values using getopts. This allow you to write things as ./myshell_script -a a -b b -c c -d d -d e -f f which is equivalent to any permutation of it ./myshellscript -f f -d d -e e -b b -c c -a a.

最好不要依赖参数命令,而是使用getopts将它们分配给明确的值。这允许你把东西写成./myshell_script -a a -b b -c c -d d -d e -f f,它相当于它的任何排列./myshellscript -f f -d d -e e -b b -c c -a a。

Not having to worry about order is well worth the couple of extra lines at the beginning of the script and extra characters in its call.

不必担心订单是值得在脚本开头的几行额外的行和其调用中的额外字符。

Getopts Tutorial on Bask-hackers

关于Bask-hackers的Getopts教程

#3


0  

myshellscript

myshellscript

#!/bin/bash
grep -oP 'b\s*\K[^ ]+' <<<$*

Test:

测试:

% myshellscript a b c d e f
c
% myshellscript f d e b c a
c