0

I'm facing some problems in writing to the file in unix

[ -s $PWD/MEN/*sub.wav ] && echo "File there" || echo "File Not there" > temp.csv

I'm trying this unix command but it is not writing to the file temp.csv.

2

If you break your command then these is equivalent

[ -s $PWD/MEN/*sub.wav ]

It will execute anyway if your pattern "$PWD"/MEN/*sub.wav doesn't matches more than a single filename. Then comes

echo "File There"

The shell try to execute this command and in your case it had executed sucessfully and then comes ||This means that if left part fails then execute right part. As our left part is executed then right part will never be executed. If you want to write File there to temp.csv then your command look like

[ -s $PWD/MEN/*sub.wav ] && echo "File there" > temp.csv || echo "File Not there" > temp.csv

or if you want to write both part then

[ -s $PWD/MEN/*sub.wav ] && echo "File there" > temp.csv && echo "File Not there" > temp.csv
3

The only thing writing to temp.csv in your command is the last echo, which only gets executed if the -s test or the first echo fails.

To output to the file properly do

if [ -s MEN/*sub.wav ]; then echo "File there"; else echo "File not there"; fi >temp.csv

or (not quite equivalently),

[ -s MEN/*sub.wav ] && echo "File there" >temp.csv || echo "File not there" >temp.csv

Also note that if your pattern MEN/*sub.wav matches more than a single filename, this would generate a syntax error in your program.

Would you want to test whether at least one name matches the pattern, and is non-empty (the -s test), then use

set -- MEN/*sub.wav

# Loop over the matching names (if any).
# Stop when we find a non-empty file.
while [ "$#" -gt 0 ] && [ ! -s "$1" ]; do
     shift
done
if [ -s "$1" ]; then
    echo File exists
else
    echo File not there
fi >temp.csv

Would you want to test whether all names that match the pattern are non-empty:

set -- MEN/*sub.wav

# Loop over the matching names (if any).
# Stop when we find an empty file.
while [ "$#" -gt 0 ] && [ -s "$1" ]; do
     shift
done
if [ "$#" -eq 0 ]; then
    echo File(s) exists
else
    echo File(s) not there
fi >temp.csv

This last piece of code relies on the shell retaining the unexpanded pattern in case there are no matching names.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.