In Bash, is this normal for a variable and function with the same name?

I have the following code in my ~ / .bashrc:

date=$(which date) date() { if [[ $1 == -R || $1 == --rfc-822 ]]; then # Output RFC-822 compliant date string. # eg Wed, 16 Dec 2009 15:18:11 +0100 $date | sed "s/[^ ][^ ]*$/$($date +%z)/" else $date " $@ " fi } 

This works great, as far as I can tell. Is there a reason why not have a variable and function with the same name?

+4
source share
3 answers

Well, if not confused. In addition, they do not match:

 $ date=/bin/ls $ type date date is hashed (/bin/date) $ type $date /bin/ls is /bin/ls $ moo=foo $ type $moo -bash: type: foo: not found $ function date() { true; } $ type date date is a function date () { true*emphasized text* } $ which true /bin/true $ type true true is a shell builtin 

Whenever you enter a command, bash looks in three different places to find this command. Priority is as follows:

  • built-in shells (help)
    • shell aliases (help alias)
    • Shell Functions (help function)
  • hashes binary files from $ PATH (first look at the "leftmost" folders)

Variables have a dollar sign prefix, which distinguishes them from all of the above. For comparison with your example: $ date and date are not the same thing. So it’s actually impossible to have the same name for a variable and function because they have different “namespaces”.

You may find this somewhat confusing, but many scripts define "method variables" at the top of the file. eg.

 SED=/bin/sed AWK=/usr/bin/awk GREP/usr/local/gnu/bin/grep 

The generally accepted task is to type the names of variables in capitals. This is useful for two purposes (besides less confusing):

  • No $ PATH
  • Validating all dependencies

You really cannot verify this:

 if [ "`which binary`" ]; then echo it\ ok to continue.. ;fi 

Because it will give you an error if the binary has not yet been hashed (found in the path folder).

+4
source

Since you should always use $ to dereference a variable in Bash, you can use whatever name you like.

Beware of redefining the global.

See also:

http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_03_02.html

+2
source

Alternative to using a variable: use the bash command keyword (see the manual or run the help command from the prompt)

 date() { case $1 in -R|--rfc-2822) command date ... ;; *) command date " $@ " ;; esac } 
+2
source

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


All Articles