5 useful bash expressions to use with IF

nonunicorn

Onelinerhub

Posted on June 30, 2022

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.

💖 💪 🙅 🚩
nonunicorn
Onelinerhub

Posted on June 30, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related