编程知识 cdmana.com

How to get parameters from Linux shell

The usage of transmitting reference

Linux Shell  How to get parameters
$# It's for Script The number of parameters
$0 yes Script Its own name
$1 It's passed on to the shell The first parameter of the script
$2 It's passed on to the shell The second parameter of the script
$@ Is a list of all parameters passed to the script
$* It shows all the parameters passed to the script in a single string , Different from position variable , Parameters can exceed 9 individual
$$ Is the current process the script is running ID Number
$? It's showing the last command The exit status of ,0 No mistakes , Others say there is a mistake

give an example

newly build test.sh

#!/bin/sh
echo "shell Script name : $0"
echo " to shell The first parameter of : $1"
echo " to shell Second parameter of : $2"

stay command Do it

chmod +x test.sh
./test.sh 4 5

Linux Shell How to get parameters Linux Shell How to get parameters

$@ and $*
The same thing

All references to all parameters

Difference

$* and $@ Represents all parameters passed to a function or script , Not double quoted (" ") Inclusion time , Are subject to "$1" "$2" … "$n" Output all parameters in the form of .

When they are double quoted (" ") Inclusion time ,"$*" All parameters will be taken as a whole , With "$1 $2 … $n" Output all parameters in the form of ;"$@" Separate parameters , With "$1" "$2" … "$n" Output all parameters in the form of .
newly build file.sh, Write the following :

#!/bin/bash
echo "-----------------"
for key in "$@"
do
echo '$@' $key
done
echo "-----------------------------"
for key2 in $*
do
echo '$*' $key2
done

1、 Quote execution and results :

[root@localhost ~]# bash file.sh linux "python c"

Linux Shell How to get parameters Linux Shell How to get parameters

2、 Execution and results without quotation marks :

[root@localhost ~]# bash file.sh linux python c

Linux Shell How to get parameters Linux Shell How to get parameters

Original address of this article :https://www.linuxprobe.com/linux-shell-get-args.html

版权声明
本文为[That's how Linux should learn]所创,转载请带上原文链接,感谢

Scroll to Top