0

Issue

I have been experiencing issues with Linux commands run in folders that contain numerically numbered files and folders; e.g., files sequentially numbered 1, 2, 3 ...

For example, if I am in a folder that contains a file or folder with a numeric name that appears in my command, the output from that command output might be truncated.

Here are some examples:

$ ls -l
total 8
drwxr-xr-x 2 victoria victoria 4096 May  7 18:34 1
drwxr-xr-x 2 victoria victoria 4096 May  7 18:14 2
-rw-r--r-- 1 victoria victoria    0 May  7 18:34 3

## fail
$ a="[CPT1A] A Selective"; echo $a
1 A Selective
$ b="[CPT2A] A Selective"; echo $b
2 A Selective
$ c="[CPT3A] A Selective"; echo $c
2 A Selective
...

## pass
$ d="[CPT4A] A Selective"; echo $d
[CPT4A] A Selective

Update/solution

... per accepted answer: quote the BASH variable, when used.

$ a="[CPT1A] A Selective"; echo $a
1 A Selective
$ a="[CPT1A] A Selective"; echo "$a"
[CPT1A] A Selective

Victoria Stuart
  • 4,610
  • 2
  • 44
  • 37

1 Answers1

3

The problem is that you aren't quoting the variable when you use it -- that is, you're using echo $a instead of echo "$a". When a variable is referenced without quotes, it gets split into words (so "[CPT1A] A Selective" becomes "[CPT1A]" "A" "Selective"), and then each of those words that contains anything that looks like a filename wildcard gets expanded into a list of matching filenames.

Square-bracket expressions like [CPT1A] are actually valid wildcard expressions that match any single character within them, so if there are files named "A", "C", "P", "T", or "1", it would expand to the matching names. If there aren't any, the wildcard expression just gets passed through intact.

Solution: double-quote variable references to avoid surprises like this. The same goes for command substitutions with $( ) (or backticks, but don't use those). There are a few places where it's safe to leave them off, like in a direct assignment, but IMO it's safer to just use them everywhere than to try to keep track of the exceptions. For example, a=$b is ok, but so is a="$b". On the other hand, export a=$b might or might not work (depending on which shell you're using), but export a="$b" will work.

BTW, shellcheck.net is good at pointing these out (along with some other common mistakes).

Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151