次のスクリプトを考えてみましょう。
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
basename $0
1)これが私のスクリプト名を表すことを知っています。しかし、どのように?文法を説明してください。どういう意味ですか$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