Linux: 대상 dir(존재하지 않는 경우) 복사
대상 디렉터리가 없는 경우 해당 디렉터리를 생성하는 명령(또는 cp 옵션)을 원합니다.
예:
cp -? file /path/to/copy/file/to/is/very/deep/there
mkdir -p "$d" && cp file "$d"
(그런 옵션은 없습니다.cp
).
다음 두 가지 모두에 해당하는 경우:
- GNU 의버사있습니다고의 .
cp
들어 (Mac 버전이 있음) - 기존 디렉토리 구조에서 복사하고 있으며 다시 작성하기만 하면 됩니다.
그러면 당신은 이것을 그것으로 할 수 있습니다.--parents
의 cp
정보 페이지(http://www.gnu.org/software/coreutils/manual/html_node/cp-invocation.html#cp-invocation 에서 또는 를 사용하여 볼 수 있습니다.info cp
또는man cp
):
--parents Form the name of each destination file by appending to the target directory a slash and the specified name of the source file. The last argument given to `cp' must be the name of an existing directory. For example, the command: cp --parents a/b/c existing_dir copies the file `a/b/c' to `existing_dir/a/b/c', creating any missing intermediate directories.
예:
/tmp $ mkdir foo
/tmp $ mkdir foo/foo
/tmp $ touch foo/foo/foo.txt
/tmp $ mkdir bar
/tmp $ cp --parents foo/foo/foo.txt bar
/tmp $ ls bar/foo/foo
foo.txt
단답형
myfile.txt
/foo/bar/myfile.txt
매개 변수:
mkdir -p /foo/bar && cp myfile.txt $_
이것은 어떻게 작동합니까?
여기에는 몇 가지 구성 요소가 있으므로 모든 구문을 단계별로 설명하겠습니다.
POSIX 표준에 지정된 대로 mkdir 유틸리티는 디렉터리를 만듭니다.그-p
문서에 따르면 인수는 mkdir를 유발합니다.
누락된 중간 경로 이름 구성 요소를 만듭니다.
전화를 걸 때 그 의미는mkdir -p /foo/bar
mkdir가 생성합니다./foo
그리고. /foo/bar
한다면/foo
하지 않습니다. (). (으)ㄹ게요. (으)ㄹ게요.-p
대신 오류를 던질 것입니다.
그&&
POSIX 표준(또는 원하는 경우 Bash 매뉴얼)에 문서화된 목록 연산자는 다음과 같은 영향을 미칩니다.cp myfile.txt $_
다음과 같은 경우에만 실행됩니다.mkdir -p /foo/bar
성공적으로 실행됩니다.이것은 다음을 의미합니다.cp
다음 경우 명령이 실행을 시도하지 않습니다.mkdir
실패할 수 있는 여러 가지 이유 중 하나로 인해 실패합니다.
막으로마지,로으,$_
는 우는두번통주과다니합로 두 번째 .cp
변수에 변수를 저장할 필요 없이 파일 경로와 같은 긴 인수를 반복하지 않도록 하는 데 유용한 "특수 매개 변수"입니다.Bash 매뉴얼에 따라 다음을 수행합니다.
이전 명령의 마지막 인수로 확장됩니다.
이경우, 이그바로입니다./foo/bar
우리는 로 넘겼습니다.mkdir
그래서 그cp
이 명이로확됨으로 됩니다.cp myfile.txt /foo/bar
를 베끼는 것myfile.txt
새로 창조된 것으로./foo/bar
디렉토리입니다.
:$_
POSIX 표준의 일부가 아니므로 이론적으로 유닉스 변종은 이 구성을 지원하지 않는 셸을 가질 수 있습니다.하지만, 저는 지원하지 않는 현대의 조개껍데기에 대해서는 모릅니다.$_
Bash, Dash, Zsh는 확실히 그렇게 할 것입니다.
마지막 메모: 이 답변의 시작 부분에 지정한 명령은 디렉토리 이름에 공백이 없다고 가정합니다.공백이 있는 이름을 처리하는 경우 다른 단어가 다른 인수로 처리되지 않도록 이름을 인용해야 합니다.mkdir
또는cp
명령은 다음과 같습니다.
mkdir -p "/my directory/name with/spaces" && cp "my filename with spaces.txt" "$_"
그렇게 오래된 질문이지만, 제가 다른 해결책을 제안할 수 있을지도 모릅니다.
당신은 할 수 .install
파일을 복사하고 "즉각" 대상 경로를 만드는 프로그램입니다.
install -D file /path/to/copy/file/to/is/very/deep/there/file
고려해야 할 몇 가지 측면이 있지만, 다음과 같습니다.
- 대상 경로뿐만 아니라 대상 파일 이름도 지정해야 합니다.
- 대상 파일은 실행 가능할 것입니다(적어도 테스트에서 본 바로는).
다음을 추가하여 #2를 쉽게 수정할 수 있습니다.-m
파일에 을 설정하는 (": " "("):-m 664
사용 권한이 있는 대상 파일을 만듭니다.rw-rw-r--
새파을만것마찬로지가과드는으로 새 처럼.touch
).
그리고 여기에 제가 영감을 받은 답변에 대한 뻔뻔한 링크가 있습니다. =)
파일이 살 구멍을 파서 "버리" 복사본이라고 부르며 원하는 것을 수행하는 셸 함수:
bury_copy() { mkdir -p `dirname $2` && cp "$1" "$2"; }
한 가지 방법이 있습니다.
mkdir -p `dirname /path/to/copy/file/to/is/very/deep/there` \
&& cp -r file /path/to/copy/file/to/is/very/deep/there
dirname
대상 디렉터리 또는 파일의 부모를 제공합니다. mkdir -p'smkname...그러면 cp -r을 호출할 때 올바른 기본 디렉터리가 있는지 확인하는 디렉터리가 만들어집니다.
상위 항목에 비해 이점은 대상 경로의 마지막 요소가 파일 이름인 경우에 사용할 수 있다는 것입니다.
OS X에서도 작동합니다.
위의 답변을 존중하여 다음과 같이 사용자 동기화를 선호합니다.
$ rsync -a directory_name /path_where_to_inject_your_directory/
예:
$ rsync -a test /usr/local/lib/
install -D file -m 644 -t /path/to/copy/file/to/is/very/deep/there
이것으로 끝입니다.
cp -vaR ./from ./to
이것은 매우 늦었지만 신인에게 도움이 될 수도 있습니다.폴더를 자동으로 생성해야 하는 경우rsync
당신의 가장 친한 친구가 되어야 합니다.
rsync /path/to/sourcefile /path/to/tragetdir/thatdoestexist/
.bashrc에 다음을 추가하기만 하면 됩니다. 필요하면 수정하십시오.Ubuntu에서 작동합니다.
mkcp() {
test -d "$2" || mkdir -p "$2"
cp -r "$1" "$2"
}
예: 'test' 파일을 대상 디렉터리 'd'에 복사하려면,
mkcp test a/b/c/d
mkcp는 먼저 대상 디렉터리가 존재하는지 여부를 확인한 다음, 존재하지 않으면 소스 파일/디렉토리를 복사합니다.
다시 시작해서 한 줄로 완벽한 해결책을 제시하는 것입니다.파일 이름을 변경하려면 mkdir에 깨끗한 dir 경로를 제공하는 방법을 포함해야 합니다.$165st는 file 또는 dir일 수 있습니다.다음 코드는 어떤 경우에도 작동해야 합니다.
fsrc=/tmp/myfile.unk
fdst=/tmp/dir1/dir2/dir3/myfile.txt
mkdir -p $(dirname ${fdst}) && cp -p ${fsrc} ${fdst}
또는 bash 특정
fsrc=/tmp/myfile.unk
fdst=/tmp/dir1/dir2/dir3/myfile.txt
mkdir -p ${fdst%/*} && cp -p ${fsrc} ${fdst}
위에서 help_asap 및 spongeman이 제안한 것처럼 'install' 명령을 사용하여 파일을 기존 디렉터리에 복사하거나 새 대상 디렉터리가 없는 경우 새로 만들 수 있습니다.
1 션옵 1install -D filename some/deep/directory/filename
을 새 디렉터리에 기본 사용 합니다.
2 션옵 2install -D filename -m640 some/deep/directory/filename
옵션 1에 따라 다르지만 파일 이름 640 권한을 부여합니다.
3 션옵 3install -D filename -m640 -t some/deep/directory/
옵션 2에 따라 파일 이름을 대상 디렉터리로 지정하므로 파일 이름을 소스와 대상 모두에 쓸 필요가 없습니다.
4 션옵 4install -D filena* -m640 -t some/deep/directory/
여러 파일에 와일드카드를 사용합니다.
Ubuntu에서 잘 작동하며 두 단계(디렉토리 생성 후 파일 복사)를 하나의 단계로 결합합니다.
스크립트를 생성하지 않고 간단한 명령만으로...
mkdir -p /destination-folder/ && cp file-name /destination-folder/
저는 CP(주 대문자)라는 CP 지원 스크립트를 작성했는데, 이는 정확히 이를 수행하기 위한 것입니다.스크립트는 입력한 경로(대상인 마지막 경로 제외)에 오류가 있는지 확인하고 모든 것이 정상이면 복사를 시작하기 전에 mkdir -p 단계를 수행하여 대상 경로를 만듭니다.이 시점에서 일반 cp 유틸리티가 인계되고 CP와 함께 사용하는 모든 스위치(예: -r, -p, -rpL)가 cp로 직접 파이프됩니다.제 스크립트를 사용하기 전에 이해해야 할 몇 가지 사항이 있습니다.
- CP --help를 수행하면 여기에 있는 모든 정보에 액세스할 수 있습니다.CP --help-all에는 의 스위치가 포함됩니다.
- 일반 cp는 대상 경로를 찾지 못하면 복사를 하지 않습니다.당신은 CP의 오타에 대한 그러한 안전망을 참조하십시오.대상이 생성되므로 대상을 /usr/share/icons 또는 /usr/share/icons로 잘못 입력하면 생성됩니다.
- 정규 cp는 기존 경로에서 동작을 모델링하는 경향이 있습니다. cp /a/b /c/d는 d의 존재 여부에 따라 달라집니다. d가 기존 폴더인 경우 cp는 b를 복사하여 /c/d/b를 만듭니다.만약 d가 존재하지 않는다면, b는 c로 복사되고 d로 이름이 바뀝니다.d가 존재하지만 파일이고 b가 파일이면 b의 복사본으로 덮어씁니다.c가 존재하지 않으면 cp는 복사를 하지 않고 종료합니다.
CP는 기존 경로에서 신호를 얻을 여유가 없기 때문에 매우 확고한 행동 패턴을 가져야 합니다.CP는 복사 중인 항목이 대상 경로에 삭제되고 대상 자체가 아니라고 가정합니다(소스 파일/폴더의 이름이 바뀐 복사본).의미:
- d가 폴더인 경우 "CP /a/b /c/d"는 /c/d/b를 생성합니다.
- /c/b의 b가 폴더인 경우 "CP /a/b/c/b"는 /c/b/b를 생성합니다.
- b와 d가 모두 파일인 경우: CP /a/b /c/d는 /c/d(여기서 d는 b의 복사본)가 됩니다.같은 상황에서 CP /a/b/c/b도 마찬가지입니다.
이 기본 CP 동작은 "--rename" 스위치를 사용하여 변경할 수 있습니다.이 경우, 다음과 같이 가정합니다.
- "CP --rename /a/b/c/d"는 b를 /c에 복사하고 복사본의 이름을 d로 변경하는 중입니다.
몇 가지 마무리 노트:CP와 마찬가지로 CP는 한 번에 여러 항목을 복사할 수 있으며 마지막 경로는 대상으로 간주됩니다.따옴표를 사용하는 한 공백이 있는 경로도 처리할 수 있습니다.
CP는 복사하기 전에 사용자가 입력한 경로를 확인하고 경로가 존재하는지 확인합니다.엄격 모드( --stract 스위치를 통해 사용 가능)에서는 복사할 모든 파일/폴더가 존재하거나 복사가 수행되지 않아야 합니다.완화 모드(--완화 모드)에서는 나열한 항목 중 하나 이상이 있으면 복사가 계속됩니다.완화 모드가 기본이며, 스위치를 통해 일시적으로 모드를 변경하거나 스크립트 시작 부분에서 변수 easy_going을 설정하여 영구적으로 모드를 변경할 수 있습니다.
설치 방법은 다음과 같습니다.
루트가 아닌 터미널에서 다음을 수행합니다.
sudo echo > /usr/bin/CP; sudo chmod +x /usr/bin/CP; sudo touch /usr/bin/CP
gedit admin:///usr/bin/CP
CP 유틸리티를 입력하고 붙여넣은 다음을 저장합니다.
#!/bin/bash
#Regular cp works with the assumption that the destination path exists and if it doesn't, it will verify that it's parent directory does.
#eg: cp /a/b /c/d will give /c/d/b if folder path /c/d already exists but will give /c/d (where d is renamed copy of b) if /c/d doesn't exists but /c does.
#CP works differently, provided that d in /c/d isn't an existing file, it assumes that you're copying item into a folder path called /c/d and will create it if it doesn't exist. so CP /a/b /c/d will always give /c/d/b unless d is an existing file. If you put the --rename switch, it will assume that you're copying into /c and renaming the singl item you're copying from b to d at the destination. Again, if /c doesn't exist, it will be created. So CP --rename /a/b /c/d will give a /c/d and if there already a folder called /c/d, contents of b will be merged into d.
#cp+ $source $destination
#mkdir -p /foo/bar && cp myfile "$_"
err=0 # error count
i=0 #item counter, doesn't include destination (starts at 1, ex. item1, item2 etc)
m=0 #cp switch counter (starts at 1, switch 1, switch2, etc)
n=1 # argument counter (aka the arguments inputed into script, those include both switches and items, aka: $1 $2 $3 $4 $5)
count_s=0
count_i=0
easy_going=true #determines how you deal with bad pathes in your copy, true will allow copy to continue provided one of the items being copied exists, false will exit script for one bad path. this setting can also be changed via the custom switches: --strict and --not-strict
verbal="-v"
help="===============================================================================\
\n CREATIVE COPY SCRIPT (CP) -- written by thebunnyrules\
\n===============================================================================\n
\n This script (CP, note capital letters) is intended to supplement \
\n your system's regular cp command (note uncapped letters). \n
\n Script's function is to check if the destination path exists \
\n before starting the copy. If it doesn't it will be created.\n
\n To make this happen, CP assumes that the item you're copying is \
\n being dropped in the destination path and is not the destination\
\n itself (aka, a renamed copy of the source file/folder). Meaning:\n
\n * \"CP /a/b /c/d\" will result in /c/d/b \
\n * even if you write \"CP /a/b /c/b\", CP will create the path /a/b, \
\n resulting in /c/b/b. \n
\n Of course, if /c/b or /c/d are existing files and /a/b is also a\
\n file, the existing destination file will simply be overwritten. \
\n This behavior can be changed with the \"--rename\" switch. In this\
\n case, it's assumed that \"CP --rename /a/b /c/d\" is copying b into /c \
\n and renaming the copy to d.\n
\n===============================================================================\
\n CP specific help: Switches and their Usages \
\n===============================================================================\n
\
\n --rename\tSee above. Ignored if copying more than one item. \n
\n --quiet\tCP is verbose by default. This quiets it.\n
\n --strict\tIf one+ of your files was not found, CP exits if\
\n\t\tyou use --rename switch with multiple items, CP \
\n\t\texits.\n
\n --relaxed\tIgnores bad paths unless they're all bad but warns\
\n\t\tyou about them. Ignores in-appropriate rename switch\
\n\t\twithout exiting. This is default behavior. You can \
\n\t\tmake strict the default behavior by editing the \
\n\t\tCP script and setting: \n
\n\t\teasy_going=false.\n
\n --help-all\tShows help specific to cp (in addition to CP)."
cp_hlp="\n\nRegular cp command's switches will still work when using CP.\
\nHere is the help out of the original cp command... \
\n\n===============================================================================\
\n cp specific help: \
\n===============================================================================\n"
outro1="\n******************************************************************************\
\n******************************************************************************\
\n******************************************************************************\
\n USE THIS SCRIPT WITH CARE, TYPOS WILL GIVE YOU PROBLEMS...\
\n******************************************************************************\
\n******************************* HIT q TO EXIT ********************************\
\n******************************************************************************"
#count and classify arguments that were inputed into script, output help message if needed
while true; do
eval input="\$$n"
in_=${input::1}
if [ -z "$input" -a $n = 1 ]; then input="--help"; fi
if [ "$input" = "-h" -o "$input" = "--help" -o "$input" = "-?" -o "$input" = "--help-all" ]; then
if [ "$input" = "--help-all" ]; then
echo -e "$help"$cp_hlp > /tmp/cp.hlp
cp --help >> /tmp/cp.hlp
echo -e "$outro1" >> /tmp/cp.hlp
cat /tmp/cp.hlp|less
cat /tmp/cp.hlp
rm /tmp/cp.hlp
else
echo -e "$help" "$outro1"|less
echo -e "$help" "$outro1"
fi
exit
fi
if [ -z "$input" ]; then
count_i=$(expr $count_i - 1 ) # remember, last item is destination and it's not included in cound
break
elif [ "$in_" = "-" ]; then
count_s=$(expr $count_s + 1 )
else
count_i=$(expr $count_i + 1 )
fi
n=$(expr $n + 1)
done
#error condition: no items to copy or no destination
if [ $count_i -lt 0 ]; then
echo "Error: You haven't listed any items for copying. Exiting." # you didn't put any items for copying
elif [ $count_i -lt 1 ]; then
echo "Error: Copying usually involves a destination. Exiting." # you put one item and no destination
fi
#reset the counter and grab content of arguments, aka: switches and item paths
n=1
while true; do
eval input="\$$n" #input=$1,$2,$3,etc...
in_=${input::1} #first letter of $input
if [ "$in_" = "-" ]; then
if [ "$input" = "--rename" ]; then
rename=true #my custom switches
elif [ "$input" = "--strict" ]; then
easy_going=false #exit script if even one of the non-destinations item is not found
elif [ "$input" = "--relaxed" ]; then
easy_going=true #continue script if at least one of the non-destination items is found
elif [ "$input" = "--quiet" ]; then
verbal=""
else
#m=$(expr $m + 1);eval switch$m="$input" #input is a switch, if it's not one of the above, assume it belongs to cp.
switch_list="$switch_list \"$input\""
fi
elif ! [ -z "$input" ]; then #if it's not a switch and input is not empty, it's a path
i=$(expr $i + 1)
if [ ! -f "$input" -a ! -d "$input" -a "$i" -le "$count_i" ]; then
err=$(expr $err + 1 ); error_list="$error_list\npath does not exit: \"b\""
else
if [ "$i" -le "$count_i" ]; then
eval item$i="$input"
item_list="$item_list \"$input\""
else
destination="$input" #destination is last items entered
fi
fi
else
i=0
m=0
n=1
break
fi
n=$(expr $n + 1)
done
#error condition: some or all item(s) being copied don't exist. easy_going: continue if at least one item exists, warn about rest, not easy_going: exit.
#echo "err=$err count_i=$count_i"
if [ "$easy_going" != true -a $err -gt 0 -a $err != $count_i ]; then
echo "Some of the paths you entered are incorrect. Script is running in strict mode and will therefore exit."
echo -e "Bad Paths: $err $error_list"
exit
fi
if [ $err = $count_i ]; then
echo "ALL THE PATHS you have entered are incorrect! Exiting."
echo -e "Bad Paths: $err $error_list"
fi
#one item to one destination:
#------------------------------
#assumes that destination is folder, it does't exist, it will create it. (so copying /a/b/c/d/firefox to /e/f/firefox will result in /e/f/firefox/firefox
#if -rename switch is given, will assume that the top element of destination path is the new name for the the item being given.
#multi-item to single destination:
#------------------------------
#assumes destination is a folder, gives error if it exists and it's a file. -rename switch will be ignored.
#ERROR CONDITIONS:
# - multiple items being sent to a destination and it's a file.
# - if -rename switch was given and multiple items are being copied, rename switch will be ignored (easy_going). if not easy_going, exit.
# - rename option but source is folder, destination is file, exit.
# - rename option but source is file and destination is folder. easy_going: option ignored.
if [ -f "$destination" ]; then
if [ $count_i -gt 1 ]; then
echo "Error: You've selected a single file as a destination and are copying multiple items to it. Exiting."; exit
elif [ -d "$item1" ]; then
echo "Error: Your destination is a file but your source is a folder. Exiting."; exit
fi
fi
if [ "$rename" = true ]; then
if [ $count_i -gt 1 ]; then
if [ $easy_going = true ]; then
echo "Warning: you choose the rename option but are copying multiple items. Ignoring Rename option. Continuing."
else
echo "Error: you choose the rename option but are copying multiple items. Script running in strict mode. Exiting."; exit
fi
elif [ -d "$destination" -a -f "$item1" ]; then
echo -n "Warning: you choose the rename option but source is a file and destination is a folder with the same name. "
if [ $easy_going = true ]; then
echo "Ignoring Rename option. Continuing."
else
echo "Script running in strict mode. Exiting."; exit
fi
else
dest_jr=$(dirname "$destination")
if [ -d "$destination" ]; then item_list="$item1/*";fi
mkdir -p "$dest_jr"
fi
else
mkdir -p "$destination"
fi
eval cp $switch_list $verbal $item_list "$destination"
cp_err="$?"
if [ "$cp_err" != 0 ]; then
echo -e "Something went wrong with the copy operation. \nExit Status: $cp_err"
else
echo "Copy operation exited with no errors."
fi
exit
cp
여러 가지 용도가 있습니다.
$ cp --help
Usage: cp [OPTION]... [-T] SOURCE DEST
or: cp [OPTION]... SOURCE... DIRECTORY
or: cp [OPTION]... -t DIRECTORY SOURCE...
Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.
@앤디 로스의 대답은 다음과 같습니다.
cp SOURCE DEST
cp
하지만 만약 당신이 그것을 사용한다면 잘못된 행동을 합니다.
cp SOURCE... DIRECTORY/
cp
.
는 "가 이 하지 않는 하기 때문에 "DEST" 이저즉가없슬이생다모래고호각다하니합시행후곳모다않아니릅는존지그는가직래인지서재하리디터렉대상용서법에사즉▁why▁i▁doesn▁indest▁withoutdest▁is▁ambiguous▁(▁perhaps▁this▁isi▁that모다저래▁usage▁"는▁think▁a니서▁the그▁directory릅▁which인▁target가"지"곳▁slash▁trailing▁exist),(▁"다),않아니각존합디'가cp
에서는 이에 대한 옵션을 추가한 적이 없습니다.
다음은 dest dir에 후행 슬래시를 적용하는 이 함수의 제 버전입니다.
cp-p() {
last=${@: -1}
if [[ $# -ge 2 && "$last" == */ ]] ; then
# cp SOURCE... DEST/
mkdir -p "$last" && cp "$@"
else
echo "cp-p: (copy, creating parent dirs)"
echo "cp-p: Usage: cp-p SOURCE... DEST/"
fi
}
방금 같은 문제가 있었습니다.제 접근 방식은 다음과 같이 파일을 아카이브에 저장하는 것이었습니다.
tar cf your_archive.tar file1 /path/to/file2 path/to/even/deeper/file3
tar는 자동으로 파일을 아카이브 내의 적절한 구조에 저장합니다.실행하는 경우
tar xf your_archive.tar
파일이 원하는 디렉터리 구조로 추출됩니다.
강력하게 제안합니다.ditto
효과가 있습니다.
ditto my/location/poop.txt this/doesnt/exist/yet/poop.txt
원본에서 존재하지 않는 경로로 복사
mkdir –p /destination && cp –r /source/ $_
참고: 이 명령은 모든 파일을 복사합니다.
cp –r
및 를 복사할 수 .
$_
명령에서 된 work as 로 작업)
명령어로 할 수 는 하위명령수줄스를트하의나위만한들기에서,find
예를 들어:
set +H; echo -e "#!/bin/sh\nmkdir -p \$(dirname \"\$2\"); cp \"\$1\" \"$2\"\;" > ~/local/bin/cpmkdir; chmod +x ~/local/bin/cpmkdir
그런 다음 다음과 같이 사용할 수 있습니다.
find -name files_you_re_lookin_for.* -exec cpmkdir {} ../extracted_copy/{} \;
rsync file /path/to/copy/file/to/is/very/deep/there
만약 당신이 적절한 종류의 것을 가지고 있다면, 이것은 효과가 있을 것입니다.rsync
.
사용할 수 있습니다.find
와 함께Perl
명령은 다음과 같습니다.
find file | perl -lne '$t = "/path/to/copy/file/to/is/very/deep/there/"; /^(.+)\/.+$/; `mkdir -p $t$1` unless(-d "$t$1"); `cp $_ $t$_` unless(-f "$t$_");'
" " " 를 .$t
만약 존재하지 않는다면 말입니다.보다 ㅠㅠㅠㅠㅠㅠㅠfile
안으로$t
이외에는 않는 한file
는 내에존다니 안에 합니다.$t
.
이것은 MacOS에서 GNU /bin/bash 버전 3.2에서 작동합니다(Catalina와 Big Sur 모두에서 테스트됨).
cp -Rv <existing-source-folder>/ <non-existing-2becreated-destination-folder>
"v" 옵션은 자세한 내용을 나타냅니다.
그리고 저는 "-R" 옵션을 "재귀적"이라고 생각합니다.
-R에 대한 인간의 전체 설명은 다음과 같습니다.
source_file이 디렉터리를 지정하면 cp는 디렉터리와 해당 지점에 연결된 전체 하위 트리를 복사합니다.source_file이 /로 끝나는 경우 디렉터리 자체가 아닌 디렉터리의 내용이 복사됩니다.또한 이 옵션을 사용하면 심볼릭 링크가 간접적으로 복사되지 않고 복사되며 cp가 특수 파일을 일반 파일로 복사하지 않고 생성합니다.생성된 디렉토리는 프로세스의 umask에 의해 수정되지 않은 해당 원본 디렉토리와 동일한 모드를 가집니다.
-R 모드에서는 오류가 감지되더라도 cp는 복사를 계속합니다.
cp는 하드 링크된 파일을 별도의 파일로 복사합니다.하드 링크를 보존해야 하는 경우 tar(1), cpio(1) 또는 pax(1)를 대신 사용하는 것이 좋습니다.
아래 예제에서는 폴더 자체가 아닌 기존 폴더의 모든 내용을 새 폴더에 복사하도록 기존 폴더 끝에 "/"를 사용하고 있습니다.
cp -Rv existingfolder/ newfolder
먹어봐.
macOS에만 해당
rsync -R <source file path> destination_folder
macOS의 경우 -- cp의 부모 옵션이 작동하지 않습니다.
다른 많은 솔루션은 이스케이프해야 하는 파일이나 폴더에서 작동하지 않습니다.다음은 파일 및 폴더에 사용할 수 있고 공백 및 기타 특수 문자를 이스케이프하는 솔루션입니다.일부 팬시어 옵션에 액세스할 수 없는 비지박스 재 셸에서 테스트했습니다.
export file="annoying folder/bar.txt"
export new_parent="/tmp/"
# Creates /tmp/annoying folder/
mkdir -p "$(dirname "$new_folder/$file")"
# Copies file to /tmp/annoying folder/bar.txt
cp -r "$file" "$new_folder/$file"
이것은 또한 당신이 생략하는 경우에도 작동할 것입니다.bar.txt
전체 폴더의 재귀 복사본이 필요한 경우
당신이 다음과 같은 일을 하고 있다고 가정해 보겠습니다.
cp file1.txt A/B/C/D/파일.txt
여기서 A/B/C/D는 아직 존재하지 않는 디렉토리입니다.
가능한 해결책은 다음과 같습니다.
DIR=$(dirname A/B/C/D/file.txt)
# DIR= "A/B/C/D"
mkdir -p $DIR
cp file1.txt A/B/C/D/file.txt
그게 도움이 되길 바랍니다!
간단하죠.
cp -a * /path/to/dst/
그 묘기를 부려야 합니다.
언급URL : https://stackoverflow.com/questions/1529946/linux-copy-and-create-destination-dir-if-it-does-not-exist
'programing' 카테고리의 다른 글
게시물:복합 키를 사용하는 방법? (0) | 2023.05.07 |
---|---|
WPF 문자열 형식={0:C} 달러로 표시 (0) | 2023.05.07 |
MVVM을 사용하여 WPF에서 새 창을 생성하는 최상의 방법 (0) | 2023.05.07 |
SQL Server의 행 간격띄우기 (0) | 2023.05.07 |
Windows의 Git 심볼릭 링크 (0) | 2023.05.07 |