因此,我查看了此处的很多条目,但无法弄清楚我在这里做错了什么。我是脚本新手,想知道为什么这不起作用:
输入是
./filedirarg.sh /var/logs fileordir.sh
脚本是
#! /bin/bash
echo "Running file or directory evaluation script"
LIST=$@
if [ -f $LIST ]
then
echo "The entry ${LIST} is a file"
elif [ -d $LIST ]
then
echo "The entry ${LIST} is a directory"
fi
这导致
./filedirarg.sh: line 4: [: /var/logs: binary operator expected
./filedirarg.sh: line 7: [: /var/logs: binary operator expected
它运行良好
./filedirarg.sh fileordir.sh
$LIST
在评估中引用会导致除第一个 echo 语句之外没有输出。
答案1
我认为[ -f … ]
(或test -f …
)只需要一个参数。当你运行
./filedirarg.sh /var/logs fileordir.sh
有两个。 和 一样[ -d … ]
。
这是一个快速修复:
#! /bin/bash
echo "Running file or directory evaluation script"
for file ; do
if [ -f "$file" ]
then
echo "The entry '$file' is a file"
elif [ -d "$file" ]
then
echo "The entry '$file' is a directory"
fi
done
感谢引用,它应该适用于带空格的名称(例如./filedirarg.sh "file name with spaces"
)。
另请注意,for file ; do
相当于for file in "$@" ; do
。
答案2
预期二元运算符
如果[-f $列表}
以上}
应该是]
,正如壳牌检测:
$ shellcheck myscript
Line 4:
if [ -f $LIST }
^-- SC1009: The mentioned parser error was in this if expression.
^-- SC1073: Couldn't parse this test expression.
^-- SC1072: Expected test to end here (don't wrap commands in []/[[]]). Fix any mentioned problems and try again.
$