In the end, we print the results in our desired way using echo. If that is the case, we remove the dot part from the file name - for example, the extension part. We check if the file detected is of type file using the -f flag in the loop. # Iterating over everything in the folder Remember from earlier that $allFile has a value of ls $cDir.
#LINUX FIND FILE BY EXTENSION DRIVER#
Using Windows Expand Tool for Driver CAB Files # Checking if the last value of the path is '/' or not: Here, we check if the last value of the path provided is not /, and if that is not the case, we add it to the end to avoid any errors. Now, we start extracting the files available in the directory (of course, if it’s valid) in the allFile variable using the simple ls command, which runs in Linux as well as PowerShell in Windows operating systems.If it does not exist, we exit the script.e # Checking if the directory exists:Įcho " Directory $cDir doesn't exist!" Next, we check if the directory provided by the user exists or not.# Checking if arguments have been provided:ĬDir=$(pwd) # Setting the cDir variable to current directoryĮcho " Setting the directory to $cDir"
#LINUX FIND FILE BY EXTENSION CODE#
The following code snippet uses an if statement becoming equal = to zero 0, which would mean that no arguments have been provided in that case, we would use pwd or our current working directory as the default argument. First, we will check if the user has provided the proper arguments or not.You can use this code anywhere in your script if you want to. We have written a bash script for demonstration purposes. We want to slice this string into two parts by separating the name server and the extension py.
![linux find file by extension linux find file by extension](https://i1.wp.com/www.preprogrammer.com/wp-content/uploads/2016/09/Linux-Important-Facts-About-Filenames.jpg)
For example, there is a python file with the name server.py.
![linux find file by extension linux find file by extension](https://www.lifewire.com/thmb/keXP0OhZNVEy8_s3P93AkrhkgB4=/1202x699/filters:no_upscale():max_bytes(150000):strip_icc()/003_uses-of-linux-command-find-2201100-5bd8f3a846e0fb00838e2b33.jpg)
Suppose you find yourself in a situation where you want to extract a filename and its extension separately in a bash script. Executing the Bash File to Get File Name and Extensionīash scripting is becoming quite popular in these recent years, be it for your everyday Linux administration task or an entire DevOps automation task.