Copy and overwrite a file in shell script

只谈情不闲聊 提交于 2019-12-21 09:17:00

问题


I want to copy a certain file to a location, irrespective of that file already exists in the destination or not. I'm trying to copy through shell script.But the file is not getting copied. I'm using the following command

/bin/cp -rf /source/file /destination

but that doesn't work.


回答1:


This question has been already discussed, however you can write a little script like this:

#!/bin/bash
if [ ! -d "$2" ]; then
  mkdir -p "$2"
fi
cp -R "$1" "$2"



回答2:


Your problem might be caused by an alias for cp command created in your system by default (you can see al your aliases by typing "alias"). For example, my system has the following alis by default: alias cp='cp -i', where -i overrides -f option, i.e. cp will always prompt for overwriting confirmation.

What you need in such case (that'll actually work even if you don't have an alias) is to feed "yes" to that confirmation. To do that simply modify your cp command to look like this:

yes | cp /source/file /destination




回答3:


Use

cp -fr /source/file /destination

this should probably solve the problem.




回答4:


/bin/cp -rf src dst or /usr/bin/env cp -rf



来源:https://stackoverflow.com/questions/13855904/copy-and-overwrite-a-file-in-shell-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!