Frage

I can't understand why my shell script is outputting the following and I was wondering if someone could explan what is happening.

script:

#!/bin/bash
thisCommand="echo"
thatCommand="echo"

LOGPATH=bar
ID=foo
thisCommand="$thisCommand \$(ls -1t $LOGPATH/$ID* )"

ID=random
thatCommand="$thatCommand \$(ls -1t $LOGPATH/$ID* )"

echo $thisCommand
echo $thatCommand

output:

echo $(ls -1t bar/foo345 bar/foo346 )
echo $(ls -1t bar/random* )

Where bar/foo345 and bar/foo346 exist but bar/random* doesn't.

So here the wildcard is only replicated with the actual files if they exist. Shouldn't the shell script either just stick to the wildcard or replace the flie names and ls throw an error if it doesn't exist?

War es hilfreich?

Lösung

You can use shopt command to change this behavior:

shopt -s nullglob

Which will not echo * for some glob pattern that cannot be expanded.

As per BASH manual:

nullglob

If set, bash allows patterns which match no files (see Pathname Expansion above) to expand to a null string, rather than themselves.

Andere Tipps

If you quote the parameter expansion, file name generation will not be attempted:

$ echo "$thisCommand"
echo $(ls -1t bar/foo* )
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top