On my command line, why does echo $ 0 return "-"?

When I type echo $0 , I see -

I expect to see bash or some file name, what does it mean if I just get a "-" ?

+4
source share
3 answers

A hyphen in front of $0 means that this program is a login shell.

note: $0 does not always contain the exact path to the executable executable file, as there is a way to override it when calling execve(2) .

+6
source

I get '- bash', a few weeks ago, I played with changing the name of the process visible when running ps or top/htop or echo $0 . To answer your question directly, I don’t think it means anything. Echo is a built-in function of bash, so when it checks the argument list, bash actually does the checking and sees itself there.

Your intuition is correct, if you wrote echo $0 in a script file and ran it, you will see the script file name.

+1
source

So, based on one of your comments, you really want to know how to determine which shell you are using; you suggested that $0 was the solution, and asked about it, but as you saw, $0 will not reliably tell you what you need to know.

If you use bash, then several unexposed variables will be set, including $BASH_VERSION . If you use tcsh, then the shell variables $tcsh and $version will be set. (Note that $version is an overly generic name, I ran into problems when some kind of system-run script sets it and compresses a tcsh-specific variable, but $tcsh should be reliable.)

The real problem is that the syntax of bash and tcsh is basically incompatible. Perhaps you can write a script that can be executed when called (via . Or source ) from tcsh or bash, but that would be complicated and ugly.

The usual approach is to have separate installation files, one for each shell you use. For example, if you use bash, you can run

 . ~/setup.bash 

or

 . ~/setup.sh 

and if you use tcsh, you can run

 source ~/setup.tcsh 

or

 source ~/setup.csh 

Versions of .sh or .csh refer to the ancestors of both shells; it makes sense to use these suffixes if you are not using any bash-specific or tcsh-specific functions.

But this requires knowing which shell you are using.

Perhaps you could create an alias in your .cshrc , .tcshrc, or .login , and an alias or function in your .profile , .bash_profile , or .bashrc`, which is called depending on what script you need.

Or, if you want to configure it every time you log in or every time you launch a new interactive shell, you can put the commands directly into the corresponding shell launch files. Of course, the teams will be different for tcsh vs. bash .

+1
source

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


All Articles