Delete the file using `rm` command:
`rm` command can be used with option and without the option for the different types of delete. The syntax of the `rm` command is given below.
Syntax:
‘-i’ option can be used with `rm` command to provide a prompt before deleting any file to prevent accidental deletion. ‘-f’ option can be used with `rm` command to remove any file forcefully. The different uses of the `rm` command are shown below.
Example-1: Delete the file using `rm` command without the option
You can apply the ‘rm’ command to remove an existing file. In the following script, an empty file is created by using the ‘touch’ command to test ‘rm‘ command. Next, ‘rm’ command is used to remove the file, test.txt.
# Set the filename
filename='test.txt'
# Create an empty file
touch $filename
# Check the file is exists or not
if [ -f $filename ]; then
rm test.txt
echo "$filename is removed"
fi
Output:
Example-2: Delete the file using `rm` command with -i option
The following script will ask for permission from the user before removing the file for ‘-i’ option. Here, the filename will be taken from the user as input. If the file exists and the user press ‘n’ then the file will not remove otherwise the file will remove.
# Take the filename
read -p 'Enter the filename to delete: ' filename
# Check the file is exists or not
if [ -f $filename ]; then
# Remove the file with permission
rm -i "$filename"
# Check the file is removed or not
if [ -f $filename ]; then
echo "$filename is not removed"
else
echo "$filename is removed"
fi
else
echo "File does not exist"
fi
Output:
Example-3: Delete the file using `rm` command with -v option
The following script will take the filename by a command-line argument. If the file exists then, it will print a remove message with the filename for ‘-v’ option.
# Check the file is exists or not
if [[ $1 != "" && -f $1 ]]; then
# Print remove message
rm -v $1
else
echo "Filename is not provided or filename does not exist"
fi
Output:
Example-4: Delete multiple files using `rm` command
More than one file can be deleted by using ‘rm’ command and separating the filenames with space. In the following script, multiple filenames will be taken from the command line arguments. If any file does not exist, then it will show a message otherwise filenames will be combined by the space and stored into the variable named ‘files’. Next, the rm command will be executed with the ‘files’ variable to remove multiple files.
files=""
space=" "
# Check the multiple filenames are given or not
if [ $# > 2 ]; then
# Reading argument values using loop
for argval in "$@"
do
if [ -f $argval ]; then
files+=$argval$space
else
echo "$argval does not exist"
fi
done
# Remove files
rm $files
echo "files are removed."
else
echo "Filenames are not provided, or filename does not exist"
fi
Output:
Conclusion:
The above examples show the different types of ways to delete the file using a bash script to help bash users to do this type of task easily.