in bash regarding "if" condition. How can I write in a script that will check if a text file is empty continue the script else < perform some command>?
            Asked
            
        
        
            Active
            
        
            Viewed 70 times
        
    -3
            
            
        - 
                    https://www.gnu.org/software/bash/manual/html_node/Conditional-Constructs.html – Shawn Oct 14 '22 at 10:53
- 
                    In the shell, don't think of it as "if condition". It is "if command". If the command succeeds (returns 0), then do something. The syntax is straightforward: `if cmd; then cmd; else cmd; fi`. Each command can be a block. eg `if cmd1; cmd2; cmd3 && cmd4; cmd5 | cmd6; then cmd7; cmd8; fi`. (In that case, `cmd7 and cmd8` are executed if `cmd6` returns 0.) – William Pursell Oct 14 '22 at 11:25
- 
                    what the command to check whether text file is empty so continue the script and if the file contains strings perform certain command? – Alex Zarankin Oct 14 '22 at 11:35
- 
                    1`if test -s file; then echo file exists and is non-empty; fi` and `if grep -q pattern file; then echo file contains pattern; fi` – William Pursell Oct 14 '22 at 11:52
1 Answers
0
            
            
        You probably want to this:
if  [ -s "$file" ]
then
    echo 'file exist and non-empty'
    # perform some command then exit?
fi
The [ is a short-hand for the command test.  See the man bash in the "SHELL BUILTIN COMMANDS" for details.  man test is what I end up using most of the time, though.
If it is important that it is a text file, then preferably check the file has the expected extension (here .txt):
if [ "${file: -4}" = ".txt" ]
then
   echo file is a text file (extension)
fi
"${file: -4} means extract the last 4 letters from the variable file, and we then compare that with ".txt".
Failing that you use the file utility to inspect the content of the file:
if [ "`file -b "$file"`" = "ASCII text" ]
then
   echo file is a text file (content)
fi
 
    
    
        Allan Wind
        
- 23,068
- 5
- 28
- 38
- 
                    This answer is ok, though I'd love to get more discussion about what `[` actually is and a link to `man test` or sth. – Guss Oct 15 '22 at 00:33
- 
                    
- 
                    
- 
                    
- 
                    1Right - you actually reversed the check: if the file isn't empty (and possibly is a text file) "do something". But was worth pointing out. Thx. – Guss Oct 15 '22 at 00:57
 
    