-2

For the following script:

for f in $FILES
do

    fname="$(basename "${f}")"
    fn="${fname:6:2}"
    if [["$fn" == "01"]]; then #error here
        echo "yes"
    fi
done

1 Answers1

4

You have a rather simple syntax problem. Just put spaces before and after the test construct, as in

if [[ "$fn" == "01" ]]; then ...

and it should work.

The reason is that the [[ is acually a bash keyword, not an operator, and as such has to be placed "standalone" (similar to the if etc.).

One of your files seems to be called 01. With your syntax, the shell would see the keyword if, which it expects to be followed by a command whose return code is to be evaluated. In your code, it would consider [[01 to be that command, which obviously doesn't exist. That is also the reason for your error message.

If you want to learn more about shell scripting, and since you seem to be using the bash (or ksh) as indicated by your use of the double-bracket test operator, you may want to look into the Bash Guide (as per @terdon's recommendation) and, later, the Advanced Bash scripting guide (once you are "hardened" against the not-so-good practices it sometimes contains) for in-depth information.

AdminBee
  • 22,803
  • 2
    Note that that guide is not very good. It has a lot of examples that include bad practices. Things like for file in $(find ... ) do and the like. It is useful for some things, but shouldn't be taken as authoritative at all. – terdon Jan 16 '20 at 12:15
  • You are probably right, perhaps you can point to a better one ...? – AdminBee Jan 16 '20 at 12:16
  • 2
    Grey Cat's Wiki is excellent. But don't get me wrong, I often look things up in the ABS too. Just keep in mind that it isn't perfect. It's fine for things like how string manipulation works, but not for more general coding advice. – terdon Jan 16 '20 at 12:18