7

I'm trying to create an array of file names, based on two variable and using brace expansion, like this:

#!/bin/bash
altdir=/usr
arg=abc
tries=({.,$altdir}/{$arg,$arg/main}.{tex,ltx,drv,dtx})
for i in "${tries[@]}"; do echo $i; done

The last statement list the files I want correctly:

./abc.tex
./abc.ltx
./abc.drv
./abc.dtx
./abc/main.tex
./abc/main.ltx
./abc/main.drv
./abc/main.dtx
/usr/abc.tex
/usr/abc.ltx
/usr/abc.drv
/usr/abc.dtx
/usr/abc/main.tex
/usr/abc/main.ltx
/usr/abc/main.drv
/usr/abc/main.dtx

But shellcheck tells me that the two variables, altdir and arg, appear to be unused:

$ shellcheck testscript

In testscript line 3:
    altdir=/usr
    ^-- SC2034: altdir appears unused. Verify it or export it.

In testscript line 4:
    arg=abc
    ^-- SC2034: arg appears unused. Verify it or export it.

Is there a better way to do this?

  • 2
    It seems as a shellcheck's bug. They seem to fail to recognise a variable usage in brace expansion. – choroba Sep 16 '15 at 15:08
  • I think you're fine. An unused variable warning is meant to catch typos; if you know you aren't making a mistake, it's safe to ignore it. – Tom Hunt Sep 16 '15 at 15:22
  • @WyboDekker shellcheck's commit history suggests that this was fixed in 0.3.8. Your version 0.3.4 is over a year old. – that other guy Sep 17 '15 at 18:21
5

A workaround can be:

#!/bin/bash

unset altdir
unset arg

: "${altdir:=/usr}"
: "${arg:=abc}"

tries=({.,"$altdir"}/{"$arg","$arg"/main}.{tex,ltx,drv,dtx})
for i in "${tries[@]}"; do echo "$i"; done

or make shellcheck ignore SC2034 code:

shellcheck -e SC2034 testscript

(And remember to always quote your variables if you don't want list context)

  • Thanks! After all I found that the online version of shellcheck behaves differently than my Debian-8.1 version (shellcheck-0.3.4). The online version had no problem with my original script, except for the $i that should be quoted. The Debian shellcheck said about the quoted tries= statement: "Use spaces, not commas, to separate array elements. [SC2054]", which is why I removed the quotes. – Wybo Dekker Sep 17 '15 at 10:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.