So I have reviewed a lot of entries on here and cannot figure out what I am doing wrong here. I am new to scripting and want to know why this does not work:
input is
./filedirarg.sh /var/logs fileordir.shscript is
#! /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"
fiThis results in
./filedirarg.sh: line 4: [: /var/logs: binary operator expected
./filedirarg.sh: line 7: [: /var/logs: binary operator expectedIt runs fine with this
./filedirarg.sh fileordir.sh Quoting the $LIST in the evaluation results in no output except the first echo statement.
2 Answers
I think [ -f … ] (or test -f …) requires exactly one argument. When you run
./filedirarg.sh /var/logs fileordir.shthere are two. The same with [ -d … ].
This is a quick fix:
#! /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
doneThanks to quoting it should work with names with spaces (e.g. ./filedirarg.sh "file name with spaces").
Also note for file ; do is equivalent to for file in "$@" ; do.
binary operator expected
if [ -f $LIST }
The } above should be a ], as explained by ShellCheck:
$ 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.
$ 4