-1

I want to write the bash script which would accept 4 parameters: name of file, name of directory, and two strings. If there is a mistake (if first parameter is not a file or second is not a directory) then string which is a third parameter should be printed else file should be copied to directory and string which is a fourth parameter should be printed. I don't why the compiler reports mistake in line 3 with then.

  #!/bin/bash
   if [-f $1]; then
      if[-d $2] ; then
      cp $1 / $2
      echo $4
      fi
      done
  else 
      echo $3
      exit 1
      fi
Adrian
  • 17
  • 6
  • 2
    `if` statements uses `fi` not `done`. Consider using something like https://www.shellcheck.net/ to check for common bash errors – 0stone0 May 17 '21 at 13:09
  • Also, there should be spaces around the `[]`. Consider reading: [this stackoverflow post](https://stackoverflow.com/questions/19733437/getting-command-not-found-error-while-comparing-two-strings-in-bash) – 0stone0 May 17 '21 at 13:10

1 Answers1

0

If you are having problems, paste your code in at https://www.shellcheck.net/

Fix each issue, then get the report again.

The result:

#!/bin/bash
if [ -f "$1" ]; then
   if [ -d "$2" ] ; then
      cp "$1" / "$2"
      echo "$4"
   fi
else 
   echo "$3"
   exit 1
fi

I still think you are likely to have an issue at line 4 though, when it tries to copy the root directory into arg 2 without -r. I think what you meant was just

      cp "$1" "$2"

Also, you have action for the case that someone passes a valid file as $1 but a non-directory as $2. The program will just exit silently and do nothing.

Paul Hodges
  • 8,723
  • 1
  • 12
  • 28