Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do $? $0 $1 $2 mean in shell script? [duplicate]

Tags:

bash

shell

ash

I often come across $? $0 $1 $2 etc.... in shell scripting, what I know is that $? returns the exit status of the last command

echo "this will return 0" echo $? 

but what do the others do? what are they called and is there more? perhaps like $3 $4 $5 ...

like image 771
Lin Avatar asked Mar 25 '15 14:03

Lin


People also ask

What does $2 mean in shell script?

$2 is the second command-line argument passed to the shell script or function. Also, know as Positional parameters.

What is role of $0 $? And $# in shell scripting?

If you execute ./script.sh , $0 will give output ./script.sh but if you execute it with bash script.sh it will give output script.sh . Show activity on this post. They are called the Positional Parameters.

What is $? 0 in shell script?

$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded. The grep manpage states: The exit status is 0 if selected lines are found, and 1 if not found.

What is $? $# $*?

$# Stores the number of command-line arguments that were passed to the shell program. $? Stores the exit value of the last command that was executed. $0 Stores the first word of the entered command (the name of the shell program). $* Stores all the arguments that were entered on the command line ($1 $2 ...).


1 Answers

These are positional arguments of the script.

Executing

./script.sh Hello World 

Will make

$0 = ./script.sh $1 = Hello $2 = World 

Note

If you execute ./script.sh, $0 will give output ./script.sh but if you execute it with bash script.sh it will give output script.sh.

like image 98
Grzegorz Żur Avatar answered Oct 02 '22 01:10

Grzegorz Żur