2012-02-26 3 views
82

mkdir 디렉토리를 만들고 파일을 만들려면 touch을 할 수 있지만 한 번에 두 가지 작업을 수행 할 방법이 없다는 것을 알고 있습니까?유닉스 - 폴더와 파일의 경로를 만듭니다.

즉 폴더 other가 존재하지 않을 때 나는 아래 수행하려는 경우 :

cp /my/long/path/here/thing.txt /my/other/path/here/cpedthing.txt 

오류 :

cp: cannot create regular file `/my/other/path/here/cpedthing.txt': No such file or directory 

사람이에 대한 해결 방법으로 기능을 마련 했습니까?

+0

찾을 수이 : http://stackoverflow.com/questions/1529946/linux-copy-and-create-destination-dir-if-it-does-not -exist –

+0

파일 및 디렉토리의 생성이 필수적이라면이 작업을 제공하는 파일 시스템을 작성해야합니다. 표준 Linux 파일 시스템에서는 불가능합니다. –

+0

@toop 나는이 질문이 이제 1 년 반년 된 것으로 알고 있지만, 최근에 여러 답변이이 문제에 병합되었습니다. 이 유형의 것을 자주 사용해야하는 경우 [내 대답] (http://stackoverflow.com/a/19288855/119527)이 유용 할 수 있습니다. (나는 받아 들인 대답보다 더 유용 할 것이라고 주장 할 것이다. 그러나 나는 여기에 rep를 요청하지 않고있다 :-)) –

답변

94

사용 && 하나 개의 셀 라인에서 두 명령을 결합 :

COMMAND1 && COMMAND2 
mkdir -p /my/other/path/here/ && touch /my/other/path/here/cpedthing.txt 

참고 : 이전에 내가 분리 ;의 사용을 권장 두 가지 명령이 있지만 @ 트라이시스에 의해 지적한 바와 같이 COMMAND1이 실패하기 때문에 대부분의 상황에서 &&을 사용하는 것이 더 나을 것입니다. COMMAND2도 실행되지 않습니다. (그렇지 않으면이 문제는 예상되지 않았 이어질 수 있습니다.)

+9

';'와 같이'&&'를 사용하는 것이 더 좋을 것입니다. 첫 번째 명령이 실패하면 두 번째 명령도 계속 실행됩니다 (또한 실패 할 수도 있습니다) 아직 존재하지 않는다). 첫 번째 명령이 실패하면'&& '를 사용하여 두 번째 명령이 실행되지 않습니다. – trysis

+4

코드 예제의 단축키는'mkdir -p/my/other/path/here && touch $ _/cpredthing.txt'입니다. '$ _'는 본질적으로 "마지막 명령 실행의 마지막 인자"로 확장됩니다. – Sgnl

+3

@Sgnl 너는 틀림없이 정답이다. 단지 깨끗하지 않고 오류가 발생하기 쉽습니다. – meetalexjohnson

10

당신은 두 단계를 수행 할 수 있습니다

mkdir -p /my/other/path/here/ 
touch /my/other/path/here/cpedthing.txt 
12
#!/bin/sh 
for f in "[email protected]"; do mkdir -p "$(dirname "$f")"; done 
touch "[email protected]" 
+0

익명 사용자가 (편집을 통해)'dirname -z "를 사용하도록 제안했습니다. $ @"| 대신 xargs -0 mkdir -p'를 사용하십시오. – jpaugh

2
if [ ! -d /my/other ] 
then 
    mkdir /my/other/path/here 
    cp /my/long/path/here/thing.txt /my/other/path/here/cpedthing.txt 
fi 
1

필요 없음을 if then 문에 대해 ... 당신이 한 줄에 그것을 할 수 usign ;

mkdir -p /my/other/path/here;cp /my/long/path/here/thing.txt /my/other/path/here/cpedthing.txt 

- 또는 두 줄에 -

mkdir -p /my/other/path/here 
cp /my/long/path/here/thing.txt /my/other/path/here/cpedthing.txt 

- 디렉토리가 이미 존재하는 경우 -p 내가 그녀를 온 무엇 인 (오류 반환을 방지 e looking for :))

51

먼저 모든 상위 디렉토리를 만들어야합니다.

mktouch() { 
    if [ $# -lt 1 ]; then 
     echo "Missing argument"; 
     return 1; 
    fi 

    for f in "[email protected]"; do 
     mkdir -p -- "$(dirname -- "$f")" 
     touch -- "$f" 
    done 
} 

그리고 다른 명령처럼 사용 : 당신이 창조적하려면

FILE=./base/data/sounds/effects/camera_click.ogg 

mkdir -p "$(dirname "$FILE")" && touch "$FILE" 

, 당신은 make a function 수있는 특별한에서

mktouch ./base/data/sounds/effects/camera_click.ogg ./some/other/file 
+0

두 명령을 사용하여 두 단계를 거쳐야합니까? –

+0

'&&'를 사용하도록 변경했습니다 - 어떻게 되나요? –

+0

bash는 함수에서 return을 지원합니까? –

1

(하지만 흔하지 않은) 동일한 디렉토리 계층을 다시 만들려고하는 경우, cp --parents이 유용 할 수 있습니다.

/my/long는 원본 파일이있는 경우 예를 들어

, 이미 존재 my/other, 당신은이 작업을 수행 할 수 있습니다

cd /my/long 
cp --parents path/here/thing.txt /my/other 
-3

만 1 PARAM 조각 간단한하려는 경우 :

rm -rf /abs/path/to/file; #prevent cases when old file was a folder 
mkdir -p /abs/path/to/file; #make it fist as a dir 
rm -rf /abs/path/to/file; #remove the leaf of the dir preserving parents 
touch /abs/path/to/file; #create the actual file 
+2

마지막 몇 시간 † 일을 간단히 제거하려면,'rm -rf' 명령을 gratitious 던져라. † 현명한 버전 제어/백업 정책을 준수한다고 가정하면 _hours_입니다. 그렇지 않으면 수개월이 걸릴 수도 있습니다. – leftaroundabout

0

내가 본대로 유닉스 포럼에서 테스트하면 문제가 해결됩니다.

ptouch() { 
    for p in "[email protected]"; do 
     _dir="$(dirname -- "$p")" 
     [ -d "$_dir" ] || mkdir -p -- "$_dir" 
    touch -- "$p" 
    done 
} 
10

시간은/usr/빈/설치 :

install -D /my/long/path/here/thing.txt /my/other/path/here/cpedthing.txt 

당신은 소스 파일이없는 경우 :

install -D <(echo 1) /my/other/path/here/cpedthing.txt 
+1

이 보석 도구가 크게 무시된다는 사실에 놀랐습니다. man install은 설치가 더 나은 해결책임을 보여줍니다. –

2

이 내가 할 것 인 것이다 :

mkdir -p /my/other/path/here && touch $_/cpredthing.txt

여기에, $_은 우리가 실행 한 이전 명령의 마지막 인수를 나타내는 변수입니다.

항상 당신이, 당신이 그렇게처럼 echo 명령을 사용하여 테스트 할 수 있습니다 출력 될 일을보고 싶다면 :

mkdir -p /code/temp/other/path/here 
touch /code/temp/other/path/here/cpredthing.txt 

:로 출력

echo mkdir -p /code/temp/other/path/here && echo touch $_/cpredthing.txt

보너스로 중괄호 확장을 사용하여 여러 파일을 동시에 작성할 수 있습니다 (예 :

mkdir -p /code/temp/other/path/here && 
touch $_/{cpredthing.txt,anotherfile,somescript.sh} 
)

다시 echo와 완전히 검증 :

mkdir -p /code/temp/other/path/here 
touch /code/temp/other/path/here/cpredthing.txt /code/temp/other/path/here/anotherfile /code/temp/other/path/here/somescript.sh 
관련 문제