5/8/2023 0 Comments Command presence![]() ![]() Similarly we use single brackets in this example to check if the directory is preset within shell script. We can use -d attribute within single or double brackets ] to check if directory exists. #!/bin/bash FILE= "/etc/passwd" ] & echo " $FILE exists and not empty" || echo " $FILE doesn't exist or is empty"ģ.1: Method-1: Using double or single brackets ![]() Similarly with test command we can use & and || operator to check the file in single line command inside our shell script. #!/bin/bash FILE= "/etc/passwd" test -s $FILE & echo " $FILE exists and not empty" || echo " $FILE doesn't exist or is empty" We can use both double or single brackets for such one liner but as I said earlier I would recommend using double brackets. Using test command we combine -s attribute to check if file exists and is empty or has some content: #!/bin/bash FILE= "/etc/passwd" if test -s $FILE then echo " $FILE exists and not empty" To check if the file exists and if it is empty or if it has some content then we use " -s" attributeĢ.1: Method-1: Using single or double bracketsĬheck if file exists and empty or not empty using double brackets ] #!/bin/bash FILE= "/etc/passwd" if ] then echo " $FILE exists and not empty"Įlse echo " $FILE doesn't exist or is empty"Ĭheck if file exists and empty or not empty using double brackets if then echo " $FILE exists and not empty" Bash/Shell: Check if file exists (is empty or not empty) If the first condition returns FALSE then statement with || will be executed.ĪLSO READ: How to count occurrences of word in file using shell script in Linux 2. The statement after & will be executed if SUCCESS. #!/bin/bash FILE= "/etc/passwd" ] & echo " $FILE exists" || echo " $FILE missing" I would recommend always to use double brackets when you are writing one liner code in shell as it minimises the risk of getting warnings on the console when word splitting takes place. ![]() We can use single or double brackets here in this example. #!/bin/bash FILE= "/etc/passwd" if test -f $FILE then echo " $FILE exists" Test command is used to check file types and compare values. Using single brackets #!/bin/bash FILE= "/etc/passwd" if then echo " $FILE exists" Using double brackets ] #!/bin/bash FILE= "/etc/passwd" if ] then echo " $FILE exists" ALSO READ: Journalctl cheat sheet with 10+ commands to filter systemd logsġ.1: Method-1: Using single or double brackets ![]()
0 Comments
Leave a Reply. |