我正试图使用下面的脚本来获取服务器上某些站点的磁盘使用情况,但每当我尝试运行它时,都会收到这个错误:
args.sh: line 50: syntax error near unexpected token `fi'
args.sh: line 50: `fi'
我看不到任何语法错误,但我显然做错了什么。有人能告诉我发生了什么事吗?
这是我的代码:
#!/bin/bash
prefix="/var/www/html/"
suffix=".example.com"
path="$prefix$1$suffix"
args_length="$#"
paths_array=[]
args_array=("$@")
# If there is one argument, calculate disk usage of given site.
if [ args_length -eq 1];
then echo "Calculating disk usage..."
output=$(du -sh $path)
echo "This site is currently using $output"
exit 1
# If there are no arguments, calculate disk usage of all sites.
elif [ args_length -lt 1];
then echo "Calculating disk usage for all sites..."
# I haven't done this part yet!
exit 1
# If there is more than one site, calculate their disk usage
elif [ args_length > 1];
then echo "Calculating disk usage for selected sites..."
#Save arguments to sites_array
for x in args_array; do
paths_array[x] = args_array[x]
done
#Loop through array, creating paths.
for i in paths_array; do
site = paths_array[i]
paths_array[i] = "$prefix$site$suffix"
done
#Print out disk usage for each path in array.
for y in paths_array; do
output = $(du -sh $paths_array[y])
echo "This site is currently using $output"
fi
旁注:对于我还没有写的部分,有人能告诉我应该如何将当前工作目录中所有文件夹的名称保存到数组中吗?我听说解析"ls"的输出是个坏主意,所以我正在寻找一个替代方案,如果有人有的话。
您所拥有的是真正的关闭-您只是在这里遇到了一些不同的小语法错误。
语法错误:
- 您没有用
done
关闭上一个for
循环,因此fi
上出现语法错误:解释器认为它仍在循环中 - 您在
if
语句中的变量名开头删除了$
(例如args_length
与$args_length
)。因此,bash将其解释为字符串-args length-而不是args_length
变量的值 - 您在
=
周围放置空格。在bash中,当您为变量赋值时,=
周围不能有空格。相反,它应该总是像:name="value"
- 在
if
语句中,您的右括号(]
)前缺少空格
此代码有效:
#!/bin/bash
prefix="/var/www/html/"
suffix=".example.com"
path="$prefix$1$suffix"
args_length="$#"
paths_array=[]
args_array=("$@")
# If there is one argument, calculate disk usage of given site.
if [ $args_length -eq 1 ];
then echo "Calculating disk usage..."
output=$(du -sh $path)
echo "This site is currently using $output"
exit 1
# If there are no arguments, calculate disk usage of all sites.
elif [ $args_length -lt 1 ];
then echo "Calculating disk usage for all sites..."
# I haven't done this part yet!
exit 1
# If there is more than one site, calculate their disk usage
elif [ $args_length -gt 1 ];
then echo "Calculating disk usage for selected sites..."
#Save arguments to sites_array
for x in args_array; do
paths_array[x]=$args_array[x]
done
#Loop through array, creating paths.
for i in paths_array; do
site=$paths_array[i]
$paths_array[i]="$prefix$site$suffix"
done
#Print out disk usage for each path in array.
for y in paths_array; do
output=$(du -sh $paths_array[y])
echo "This site is currently using $output"
done
fi
哪个输出:
Calculating disk usage for all sites...
bash中的这类错误非常常见,很难确定,所以当它们发生时,只需一步一个脚印,重读代码,并尝试理解您所遇到的错误。