How to get CLI parameter from bash?

test.sh parameter

in test.sh, how can I get the parameter?

+3
source share
6 answers

If this is a single parameter, you use $1( $2and so on, $0is the name of the script). Then, to get ALL parameters, you use$@

+8
source

Access $0through $9( $0is the name of the script). Alternatively, $*returns a list of all parameters.

If you want to access parameters one by one or want to access parameters beyond the 9th, you can shiftparameters:

echo $1
shift
echo $1

When called like this:

./script.sh foo bar

will produce:

foo
bar
+4
source

$NUM, NUM - , . $0 - , script. $# .

test.sh alpha beta gamma
echo $0
echo $1
echo $2
echo $3
echo $#

test.sh
alpha
beta
gamma
3

+1

echo "$ @";

0
source

You can also use shiftto "shift" the parameters. $1contains the first parameter. If you call shift, then the second parameter will be "shifted" by $1, etc.

0
source

At least in Bash, you can make any of them to access any parameter, including 10 or more:

echo "${10}"
echo "${@:10:1}"

To iterate over all parameters:

for arg
do
    echo "$arg"
done

This form implies for arg in "$@"

0
source

Source: https://habr.com/ru/post/1751577/


All Articles