How to use Condition if file or directory exists on Bash Script on Ubuntu 22.04
To Use Condition If A File Or Directory Exists On Bash Script On Ubuntu 22.04
Introduction:
By using bash script you can easily find out if a regular file does or does not exist in Bash shell. The -d flag tests whether the provided name exists and is a directory. To test for regular files instead, we can use the -f flag. To test for both files and directories, we can use the -e flag.
Procedure:
Step 1: Check the OS version by using the below command
root@linuxhelp:~# lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 22.04.3 LTS
Release: 22.04
Codename: jammy
Step 2: Create a file by using Vim editor by using the below command
root@linuxhelp:~# vim test.sh
Add the following lines in the file
#!/bin/bash
[ -f /etc/resolve.conf ] &&
echo "File exists" ||
echo "File does not exists"
Step 3: Now give execute permission by using the following command
root@linuxhelp:~# chmod +x test.sh
Step 4: Run the script by using the below command
root@linuxhelp:~# ./test.sh
File does not exist
Step 5: Change the line in the file
root@linuxhelp:~# vim test.sh
[ -f /etc/resolv.conf ] &&
Step 6: Again run the script by using the below command
root@linuxhelp:~# ./test.sh
File exit
Step 7: Now search for the directory, For that edit the file by using the below command
root@linuxhelp:~# vim test.sh
Add the lines in the file
#!/bin/bash
[ -d /var/logs ] &&
echo "Directory exist" ||
echo "Directory does not exist"
Step 8: Run the script by using the below command
root@linuxhelp:~# ./test.sh
Directory does not exist
Step 9: Change the line in the file by using the below command
root@linuxhelp:~# vim test.sh
[ -d /var/log ] &&
Step 10: Run the script by using the below command
root@linuxhelp:~# ./test.sh
Directory is exist
Step 11: Now use the if condition in the file to that edit the file
root@linuxhelp:~# vim test.sh
#!/bin/bash
FILE="$1"
if [ -f "$FILE" ]
then
echo "File $FILE exist"
else
echo "$FILE does not exist" >&2
fi
Step 12: Now run the script with an argument
root@linuxhelp:~# ./test.sh /etc/passwd
File /etc/passwd exist
Step 13: Again run the script with a different argument
root@linuxhelp:~# ./test.sh /etc/passws
/etc/passws does not exist
Conclusion:
We have reached the end of this article. In this guide, we have walked you through the steps required to use Condition if a file or directory exists on Bash Script on Ubuntu 22.04. Your feedback is much welcome.
Comments ( 0 )
No comments available