LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Why $0 shows as "-bash", not the script name? (https://www.linuxquestions.org/questions/linux-newbie-8/why-%240-shows-as-bash-not-the-script-name-930266/)

johnifanx98 02-19-2012 09:48 PM

Why $0 shows as "-bash", not the script name?
 
test(){
echo $0
echo $1
echo $2
}

run "test 1 2", and it gives

-bash
1
2

I expect

test
1
2

pinga123 02-19-2012 10:06 PM

Quote:

Originally Posted by johnifanx98 (Post 4606996)
test(){
echo $0
echo $1
echo $2
}

run "test 1 2", and it gives

-bash
1
2

I expect

test
1
2

$0 is supposed to print the name of the script.
Here is the output when i run it.
Code:

test
1
2

Check the script.
Code:

test()
{
echo $0
echo $1
echo $2
}
test 1 2

Are you supplying command line arguments?

chrism01 02-20-2012 12:21 AM

How are you calling it
Code:

bash yourscript

# OR

./yourscript


AnanthaP 02-20-2012 12:30 AM

Actually the op is saying run "test 1 2".

Your $0 is run (under bash) and "test" is "shift"ed out.

OK

catkin 02-20-2012 03:08 AM

Quote:

Originally Posted by AnanthaP (Post 4607054)
Actually the op is saying run "test 1 2"

Code:

c@CW8:~$ type run
bash: type: run: not found


colucix 02-20-2012 03:32 AM

I think the most robust method is by using the appropriate bash variables. This avoid confusion between executed and sourced scripts. There is also a specific variable to retrieve function names:
Code:

#!/bin/bash
#
test () {
  echo $FUNCNAME
  echo $1
  echo $2
}

test 1 2

echo $(readlink -f "$BASH_SOURCE")

The last statement gives the full path of the script:
Code:

$ ./test.sh
test
1
2
/home/colucix/test.sh

$ . test.sh
test
1
2
/home/colucix/test.sh

$ bash test.sh
test
1
2
/home/colucix/test.sh

Hope this helps.

johnifanx98 02-20-2012 10:22 AM

Quote:

Originally Posted by colucix (Post 4607138)
I think the most robust method is by using the appropriate bash variables. This avoid confusion between executed and sourced scripts. There is also a specific variable to retrieve function names:
Code:

#!/bin/bash
#
test () {
  echo $FUNCNAME
  echo $1
  echo $2
}

test 1 2

echo $(readlink -f "$BASH_SOURCE")

The last statement gives the full path of the script:
Code:

$ ./test.sh
test
1
2
/home/colucix/test.sh

$ . test.sh
test
1
2
/home/colucix/test.sh

$ bash test.sh
test
1
2
/home/colucix/test.sh

Hope this helps.

Thanks a lot for all responses. Now I see I'm running a function not script which caused this unexpected result...


All times are GMT -5. The time now is 10:56 PM.