0

Bash expands variables before expanding pathnames (globbing). Assuming that it did it the other way round (i.e. expand pathnames before expanding variables), is it possible to write a bash script that uses both variable expansion and path expansion, such that the result is the same irrespective of the order of expansion.

I have come up with the following simple bash script.

#!/bin/bash

# Create a variable called myvar1
myvar1=~
echo $myvar1

# Use both path expansion and variable expansion with the ls command
# Assuming the variable was expanded first, the out should be the same as if the path was expanded first. Is my assumption correct?
ls $myvar1/*.txt  

Can someone verify that my script answers the question satisfactorily?

1
  • 1
    Not quite: consider a directory containing a file called $myvar1, and you do ls *. This will expand to potentially many files, one of which is $myvar1. Then (in this hypothetical world) this variable will be expanded to ~ and you will see the contents of your home directory (assuming ~ expansion still occurs after that, otherwise it will attempt to show a file literally called ~)
    – Fox
    Commented Mar 23, 2017 at 23:07

1 Answer 1

0
ls $myvar1/*.txt 

If pathnames were expanded before variables, this would look for filenames matching *.txt in a directory called $myvar1, which you probably wouldn't have. After that, it would expand $myvar1 to the path to your home directory, leaving /home/username/*.txt, which is not the same as expanding the path first and then looking for filenames ending in .txt in the home directory.

In general, since file names can contain $ signs, I think the order of expansion will always matter. Consider any script using a glob like * in a directory containing a file called $PATH.

The opposite, variables containing glob characters, is easier to work around, since you control the values of your variables.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .