0

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.

7
  • What are %cd% and %OLD_DIR%? That's not the syntax for variables in bash. Commented Feb 8, 2022 at 6:32
  • That's the syntax for variables in Windows batch scripts. Commented Feb 8, 2022 at 6:33
  • In bash you can use pushd and popd to change to a directory than return to the previous directory. Commented Feb 8, 2022 at 6:33
  • Why do you even need to save the old directory? You never change directories. Commented Feb 8, 2022 at 6:34
  • 1
    Your script is certainly not bash. Use shellcheck, to get it syntactically correct. Also, I would recommend that you go through one of the bash tutorials available on the Net. Note that bash is a bit tricky for a novice, in that you can easily write innocently looking code which causes havoc when executed. Learn at least the basics of the language, before you start programming. Commented Feb 8, 2022 at 8:12

1 Answer 1

2

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.