'wait command failing with no errors

I have the following script

command1 2>/dev/null > fileone.txt &

command2 2>/dev/null > filetwo.txt & 

wait

diff fileone.txt filetwo.txt

if [ $? != 0 ]; then
    echo "fail"
else
    echo "success"
fi

and when calling it ./myscript.sh. the command fails with no error on my console.

However echo $? returns 1

I am assuming it is a timeout issue. Is there a way to validate this? (or to set a timeout explicitly when invoking wait)



Solution 1:[1]

You can enable debugging in your code using bash strict mode.

Here is a better version of your code:

#!/bin/bash

# bash strict mode
set -Eeuo pipefail 

# trap for Error signals
trap '1>&2 echo error at line: $LINENO' ERR

ls -l 2>/dev/null > fileone.txt &

df -h  2>/dev/null > filetwo.txt & 

wait

# if there is a difference, exit code with be 1
# if there was no difference, exit code will be 0
diff fileone.txt filetwo.txt

if [ $? != 0 ]; then
    echo "fail"
else
    echo "success"
fi

and if you run this the result is:

1,7c1,12
< total 16
< -rw-r--r-- 1 shm shm   0 May  7 23:19 fileone.txt
< -rw-r--r-- 1 shm shm   0 May  7 23:19 filetwo.txt
< -rw-r--r-- 1 shm shm 273 May  7 20:08 index.html
< -rw-r--r-- 1 shm shm 491 May  7 20:07 match_html_id.sh
< -rwxr-xr-x 1 shm shm 251 May  7 23:18 s2.sh
< -rw-r--r-- 1 shm shm 413 May  7 17:40 script.sh
---
> Filesystem         Size  Used Avail Use% Mounted on
> dev                3.8G     0  3.8G   0% /dev
> run                3.9G  1.6M  3.9G   1% /run
> /dev/sda2          228G   24G  193G  11% /
> tmpfs              3.9G  228M  3.6G   6% /dev/shm
> tmpfs              3.9G   95M  3.8G   3% /tmp
> /dev/sda1          300M  288K  300M   1% /boot/efi
> tmpfs              780M   60K  780M   1% /run/user/1000
> /dev/sdb1          916G  289G  582G  34% /mnt
> /dev/mapper/ravan   75M   26M   44M  37% /home/shm/ravan
> /dev/mapper/ssh     75M  4.0M   65M   6% /home/shm/.ssh
> /dev/mapper/pas     75M  224K   69M   1% /home/shm/password
error at line: 13

So error at line: 13 which is this line:

13  diff fileone.txt filetwo.txt

And the result is right since there is a difference between two files so exit code for diff is 1.

If you change your commands to sleep 1 the result will be success.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shakiba Moshiri