Search code examples
bashshellfile-existscp

Explain me 2 lines of this shell script


What does this mean?

if [ -f $2/$1 ]

and this line:

cp $1 $2/$1

Does $2/$1 represent a file, because it's associated with -f?

#!/bin/bash
if test $# -ne 2 
then
  echo "Numbers of argument invalid"
else
  if [ -f $2/$1 ]
  then
    echo "file already exist , replace ?"
    read return
    if test $return = 'y'
    then
      cp $1 $2/$1
    else
      exit
    fi

  else
    cp $1 $2/$1
  fi
fi

Solution

  • ./script.sh "tmp.txt" "/project"
    echo $1 = tmp.txt
    echo $2 = /project
    $1 - file name
    $2 - directory
    if [ -f $2/$1 ] - checks if file exists, -f for files, -d for directory
    cp $1 $2/$1 - copy file to directory/file_name
    if [ -f /project/tmp.txt ]
    cp tmp.txt /project/tmp.txt