DEV Community

Onelinerhub
Onelinerhub

Posted on

5 useful bash expressions to use with IF

1. How to check if specific bash command is available:

if command -v CMD &> /dev/null; then echo "it exists"; fi
Enter fullscreen mode Exit fullscreen mode

Image description

Edit or save this code on github.

2. How to check if specific file exists:

if [ -f /tmp/file ]; then echo 1; fi
Enter fullscreen mode Exit fullscreen mode

Image description

Edit or save this code on github.

3. How to check if scecific directory exists:

if [ -d /tmp ]; then echo 1; fi
Enter fullscreen mode Exit fullscreen mode

Image description

Edit or save this code on github.

4. How to check if variable is empty

if [ -z "$variable" ]; then echo "\$variable is empty"; fi
Enter fullscreen mode Exit fullscreen mode

Image description

Edit or save this code on github.

5. How to check if variable is not empty

if [ ! -z "$variable" ]; then echo "\$variable is not empty"; fi
Enter fullscreen mode Exit fullscreen mode

Edit or save this code on github.

Top comments (0)