Search code examples
bashhttp-redirectls

Output redirect creates file "0"


I'm making a ls with a wildcard to check the return code in order to determine if the wildcard matches the files. While this works well, it always creates a file 0 with 0 file size. Does anybody see why?

$SSTDIR=/tmp/test
$SSTFILE=test

ls -1 $SSTDIR/$SSTFILE* &> /dev/null
if [ $? = 0 ]; then
    exit 2
fi

Any help would be appreciated :)

Edit:

# Anzahl Parameter überprüfen
if [ ${#} == "6" ]; then
    SST=$1
    IN=$2
    INFILE=$3
    SSTDIR=$4
    SSTFILE=$5
    SORT=$6
else
    echo "Verwendung: $0 \"SST Name\" \"Inbound Verzeichnis ohne /\" \"Name der eingehenden Datei\" \"Outbound Verzeichnis ohne /\" \"Name der ausgehenden Datei\" \"Stelle ab der sortiert wird\""
    exit 3 # Falsche Anzahl Parameter
fi

# Überprüfe ob das eingehende RVS Verzeichnis nicht leer ist
ls -1 $IN/$INFILE* &> /dev/null
if [ $? > 0 ]; then
    exit 1 # Keine Dateien gefunden
fi

# Überprüfe ob das SST Verzeichnis bereits Dateien beinhaltet
ls -1 $SSTDIR/$SSTFILE* &> /dev/null
if [ $? = 0 ]; then
    exit 2 # Dateien existieren bereits im SST Verzeichnis
fi

Well that's everything, there's more downwards, but that's not causing the problem, since I've tested the spots with exit.


Solution

  • It is because of that $? > 0!! The > 0 is a redirection that creates file 0! You should be aware that the [ $? > 0 ] is not a bash syntactical feature! This is normal commandline call to program named [, which is a link to test command. Try:

    $ which [
    /usr/bin/[
    

    So the "expression" you use there is not an expression, it is normal bash command (with options!). So instead, use -gt:

    if [ $? -gt 0 ] ; then ...
    

    Try man test to see all the possible options.