Bash shell 脚本关于语法和基本名称的基本问题

Gok*_*kul 3 scripting bash shell-script basename

考虑下面的脚本:

myname=`basename $0`;
for i in `ls -A`
do
 if [ $i = $myname ]
 then
  echo "Sorry i won't rename myself"
 else
  newname=`echo $i |tr a-z A-Z`
  mv $i $newname
 fi
done
Run Code Online (Sandbox Code Playgroud)

1) 我知道basename $0这里表示我的脚本名称。但是如何?请语法解释。什么$0意思?

2)在什么情况下“;” 在脚本中的语句末尾使用?例如,脚本的第一行以 ; 结尾。,而第 8 行没有。此外,我发现在某些行的末尾添加/删除分号(例如:第 1 行/第 6 行/第 8 行)并没有任何意义,无论有没有它,脚本都可以正常运行。

ter*_*don 5

$0只是一个内部 bash 变量。来自man bash

   0      Expands  to  the  name  of  the shell or shell
          script.  This is set at shell  initialization.
          If bash is invoked with a file of commands, $0
          is set to the name of that file.  If  bash  is
          started  with the -c option, then $0 is set to
          the first argument after the string to be exe?
          cuted,  if  one  is present.  Otherwise, it is
          set to the file name used to invoke  bash,  as
          given by argument zero.
Run Code Online (Sandbox Code Playgroud)

因此,$0是您的脚本的全名,例如/home/user/scripts/foobar.sh. 由于您通常不想要完整路径而只想要脚本本身的名称,因此您可以使用basename删除路径:

#!/usr/bin/env bash

echo "\$0 is $0"
echo "basename is $(basename $0)"

$ /home/terdon/scripts/foobar.sh 
$0 is /home/terdon/scripts/foobar.sh
basename is foobar.sh
Run Code Online (Sandbox Code Playgroud)

;只真正需要在bash,如果你写在同一行多个语句。在您的示例中的任何地方都不需要它:

#!/usr/bin/env bash

## Multiple statements on the same line, separate with ';'
for i in a b c; do echo $i; done

## The same thing on  many lines => no need for ';'
for i in a b c
do 
  echo $i
done
Run Code Online (Sandbox Code Playgroud)