15

I came across a shell script that contains a statement like,

if [ $val -eq $? ]

What does $? mean here?

Raj
  • 4,342
  • 9
  • 40
  • 45
  • [here is your answer][1] which may match to you question [1]: http://stackoverflow.com/questions/7101995/what-does-if-eq-0-mean-for-shell-scripts?answertab=active#tab-top – Romit M. Oct 05 '12 at 07:45
  • 1
    possible duplicate of [What are the special dollar sign shell variables?](http://stackoverflow.com/questions/5163144/what-are-the-special-dollar-sign-shell-variables) – hammar Jun 09 '13 at 15:37
  • Possible duplicate of [What are the special dollar sign shell variables?](https://stackoverflow.com/q/5163144/608639) – jww Dec 26 '18 at 11:05
  • https://swcarpentry.github.io/shell-novice/reference/ – Channa Mar 10 '20 at 19:15

6 Answers6

26

I found that the link is very useful and is the great answer. It includes clearly expression with sample.

enter image description here

biolinh
  • 2,175
  • 1
  • 24
  • 23
22
$?

returns the status of the last finished command. Status 0 tells you that everything finished ok.

In addition the $ sign is a special symbol - and in that case $val extract the value that is hold by the variable val

noobed
  • 1,329
  • 11
  • 24
17

$# = number of arguments. Answer is 3.

$@ = what parameters were passed. Answer is 1 2 3.

$? = was last command successful. Answer is 0 which means 'yes'.

ASGM
  • 11,051
  • 1
  • 32
  • 53
nickleefly
  • 3,733
  • 1
  • 29
  • 31
3

What does $? mean here?

$? is the last result of an exit-status ... 0 is by default "successfull"

bash# ls *.*
bash# echo $? 
bash# 0
bash# ls /tmp/not/existing/
bash# echo $?
bash# 2
donald123
  • 5,638
  • 3
  • 26
  • 23
2

This is the value of the exit status of the previous command. This is 0 in case of success.

mouviciel
  • 66,855
  • 13
  • 106
  • 140
-1

ls *.* or ls would produce the same result. Meaning show zero or more files with any extension in the current directory.

echo $? would display the exit status. If at least one file is displayed from the last command ,the exit status would be zero(success).

Reeno
  • 5,720
  • 11
  • 37
  • 50
  • Not exactly correct: `ls *.*` will filter the content of current directory and show only file and directories with period in them; for directories it will show the content (might depend on implementation). Also look at the following command `mkdir test && cd test && ls; echo "$?"` will return 0. However, `mkdir -m -r wo_dir && cd wo_dir && echo "test" > 1.txt && ls; echo "$?"` will return 1, with message `ls: .: Permission denied` even though the file is created. – artdanil Nov 03 '16 at 22:34