1

I have a question regarding the access to file names inside a directory.

#!/bin/bash
INPUT_DIR=/home/user/TestDir
files=$INPUT_DIR/*txt

echo $files

FileA.txt FileB.txt

But what kind of object is this ? If I access with array syntax

echo "${files[1]}"

The returned value is empty.

Peter Pisher
  • 457
  • 2
  • 11
  • The variable `files` simply contains the literal text `/home/user/TestDir/*txt`. When you `echo` it [unquoted](/q/10067266) the shell will attempt to expand the glob, and if there is a match, the expanded values are passed as arguments to `echo`. – tripleee Sep 30 '20 at 11:42

2 Answers2

2

Firstly, what you have isn't a regular expression. Expansions done by the shell involving * are called Filename Expansions, also known as "glob" expansion.

Also you are not using an array to hold your contents, but using a scalar type. When you assign the glob expression to a variable is it assigned "literally" and when you do a unquoted expansion with echo, the shell expands the variable first and then expands the glob to its resulting files. But remember that variables by default are of scalar type, they can contain only one value. For more than one value, you need arrays.

inputDir=/home/user/TestDir
files=( "$inputDir"/*txt)
printf '%s\n' "${files[@]}"

The list of elements is accessed with "${files[@]}" (the double-quotes are important here), and individual elements accessed as "${files[0]}". The things with arrays though, you cease to be POSIX compliant as they are supported in those shells.

Also don't use uppercase letters for variable names in user scripts. The uppercase variable names have special meaning and are reserved for use by the shell only.

Inian
  • 80,270
  • 14
  • 142
  • 161
0

Your files variable is a string, not an array.

If you want files to be an array you have to write

#!/bin/bash
INPUT_DIR='/home/user/TestDir'
files=( "$INPUT_DIR/"*txt )
Léa Gris
  • 17,497
  • 4
  • 32
  • 41