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

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

考虑下面的脚本:

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

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

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

答案1

$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.

因此,$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

;仅当您在同一行上编写多个语句时,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

答案2

这是什么$0意思?

来自man bash, 节PARAMETERS, 小节Special Parameters:

   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 com‐
          mands, $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 executed, if one is present.  Otherwise, it  is
          set  to  the file name used to invoke bash, as given by argument
          zero.

它说0在那里,但$0意思是因为$标识了一个参数。

您可以使用搜索键在手册页中轻松找到此类信息/。只需键入/\$0然后回车即可。在本例中, 必须用引号引起来,因为搜索$时具有特殊含义,并且需要反斜杠来“转义”这种特殊含义。\$$

什么情况下“;”在脚本中的语句末尾使用?

通常仅当您想在一行中放置至少两个语句时,例如在这种情况下您可以使用;

if [ $i = $myname ]; then

您的示例脚本中没有;需要的情况,您可以将其从第一行中删除。详细信息可以再次找到man bash

Lists
   A  list  is a sequence of one or more pipelines separated by one of the
   operators ;, &, &&, or ||, and optionally terminated by one of ;, &, or
   <newline>.

   [...]

   A sequence of one or more newlines may appear in a list  instead  of  a
   semicolon to delimit commands.

   If  a  command  is terminated by the control operator &, the shell exe‐
   cutes the command in the background in a subshell.  The shell does  not
   wait  for  the command to finish, and the return status is 0.  Commands
   separated by a ; are executed sequentially; the shell  waits  for  each
   command  to terminate in turn.  The return status is the exit status of
   the last command executed.

相关内容