Thursday, October 27, 2022

[SOLVED] Remove specific file from directory using shell script

Issue

I am trying to write a script to delete a file from a folder using shell script.

I am new to shell scripting and I tried to write one shell script program to delete a specific file from the directory. here is the sample program that I tried and I want to delete specific jar from REPORT_HOME/lib folder.

    set OLD_DIR=%cd%
echo %REPORT_HOME%
set REPORT_HOME=%REPORT_HOME%\REPORT_HOME
cd %REPORT_HOME%\lib
if [ -f antlr-2.7.7.jar ]; then
   rm -rf "antlr-2.7.7.jar"
cd %OLD_DIR%

Here REPORT_HOME is the environment variable that I set and lib is the folder from which I want to delete antlr-2.7.7.jar file.

From the command prompt, I can directly delete the specific file but I want to delete the file by running the shell script from command prompt only.

After running the above sh file from the command prompt that specific file is not getting deleted.


Solution

You are mixing in Windows CMD syntax. The proper sh script would look like

OLD_DIR=$(pwd)
echo "$REPORT_HOME"
REPORT_HOME="$REPORT_HOME/REPORT_HOME"
cd "$REPORT_HOME/lib"
if [ -f antlr-2.7.7.jar ]; then
   rm -rf "antlr-2.7.7.jar"
cd "$OLD_DIR"

However, this is humongously overcomplicated. To delete the file, just

rm -f "$REPORT_HOME/REPORT_HOME/lib/antlr-2.7.7.jar"

The -f flag says to just proceed without an error if the file doesn't exist (and also proceed without asking if there are permissions which would otherwise cause rm to prompt for a confirmation).

Perhaps see also What exactly is current working directory?

This assumes that the variable REPORT_DIR isn't empty, and doesn't start with a dash. For maximal robustness, try

rm -f -- "${REPORT_HOME?variable must be set}/REPORT_HOME/lib/antlr-2.7.7.jar"


Answered By - tripleee
Answer Checked By - Candace Johnson (WPSolving Volunteer)