문제

나는 다음과 같은 메시지를 종종 때 예를 들어,대처 dev 파일을 마스터 브랜치

cp: /Users/Masi/gitHub/shells/zsh/dvorak: No such file or directory
cp: /Users/Masi/gitHub/shells/zsh/dvorak2: No such file or directory

고 싶은 질문에 대해 생성된 폴더에 같은 내 처음 명령을 실행됩니다면 나는 예(s).

내 시 의사 코드에서는 내가 복사하려는 파일이 디렉토리는 존재하지 않습니다.

if no such a directory exists, then asks users about to create it:
   if yes, then mkdir directory AND run the initial command again
   else do noting

문제

  1. 을 변경하는 경고의 메시지: 는 파일 제어하는"같은 파일 또는 디렉토리에"-명령?
  2. 를 긁어 경로에 처음 명령을 mkidr 로 파일:방법 긁기 경로에서 초기 명령?
  3. 를 긁어에서 끝으로 선택하는 언어와 같은 AWK: 당신은 어떻게 제거하는 마지막 경기에서 경로/는 필드 구분? 내가 얼마나 있는지를 긁어 편지를 끝에서 시작으로 AWK.
도움이 되었습니까?

해결책

는 기능은 여기에서 내가 쓴 것입니다 작업에 zsh,bash 또는 ksh.

참고: 그것은 디버깅을 사용하도록 설정한(그것은 에코 명령을 실행 하는 것 보다는 오히려 그들을 실행하).당신이 언급하는 경우는 라인,그것이 실제로를 실행할 수 있습니다.

주의: 되지 않은 철저하게 테스트됩니다.

를 넣어 사용하기 위해 이 스크립트라는 파일에 cpmd/usr/local/bin (서 또는 다른 곳에서 당신의 경).그것을 활성화하기 위해,쉘 프롬프트에서 다음 명령을 입력(또는 추가 시작 시 스크립트에 대한 bash 것입 ~/.bashrc):

source cpmd

할 수 있습니다 다음 사본을 사용하여 파일을 다음과 같은 명령을 입력하십시오:

cpmd carparts /home/dave/Documents/nonexistent/newdir/

도 디렉토리"존재"또는"newdir"아직 존재하.모두 디렉토리를 만든 다음 파일 이름"carparts"복사하"newdir".

지 않는 경우 포함 슬래쉬("/")끝에,마지막 부분으로 처리되는 파일의 이름과 모든 존재하지 않는 디렉토리기 전에 만들어집니다.

cpmd supplies /home/dave/Documents/anothernew/consumables

디렉토리"anothernew"생성한 후"공급"복사와 함께 새로운 파일이름"소모품".

모든 경우 디렉토리 목적지에 이미 존재, cpmd 처럼 행동 일반 cp 명령입니다.

function cpmd {
    # copies files and makes intermediate dest. directories if they don't exist
    # for bash, ksh or zsh
    # by Dennis Williamson - 2009-06-14
    # http://stackoverflow.com/questions/993266/unable-to-make-nosuchdirectory-message-useful-in-zsh

    # WARNING: no validation is performed on $1 and $2

    # all cp commands below are hardcoded with -i (interactive) to prevent overwriting

   if [[ -n $KSH_VERSION ]]
   then
       alias local=typeset
       local func="$0"
       local lastchar="${2: -1}"
       readcmd () { read "$2?$1"; }
    elif [[ -n $ZSH_VERSION ]]
    then
        local func="$0"
        # the following two lines are split up instead of doing "${2[-1]}"
        # to keep ksh from complaining when the function is loaded
        local dest="$2"
        local lastchar="${dest[-1]}"
        readcmd () { read "$2?$1"; }
    elif [[ -n $BASH_VERSION ]]
    then
    local func="$FUNCNAME"
        local lastchar="${2:(-1)}"
        readcmd () { read -p "$1" $2; }
    else
        echo "cpmd has only been tested in bash, ksh and zsh." >&2
        return 1
    fi

    local DEBUG='echo' # COMMENT THIS OUT to make this function actually work

    if [[ ${#@} != 2 ]]
    then
        echo "$func: invalid number of parameters
Usage:
  $func source destination

  where 'destination' can include nonexistent directories (which will
  be created). You must end 'destination' with a / in order for it to
  specify only directories. Without the final slash, the 'source' will
  be copied with a new name (the last portion of 'destination'). If you
  are copying multiple files and 'destination' is not a directory, the
  copy will fail." >&2
        return 1
    fi

    local dir=$(dirname "$2")
    local response
    local nl=$'\n'

    # destination ($2) is presumed to be in one of the following formats:
    # .../existdir              test 1  (-d "$2")
    # .../existdir/existfile    test 2  (-f "$2")
    # .../existdir/newfile      test 3  (-d "$dir" && $lastchar != '/')
    # .../existdir/newdir/      (else)
    # .../newdir/newdir/        (else)
    # .../newdir/newfile        (else)

    if [[ -d "$2" || -f "$2" || (-d "$dir" && $lastchar != '/') ]]
    then
        $DEBUG cp -i "$1" "$2"
    else
        if [[ $lastchar == '/' ]]
        then
            dir="$2"
        fi
        local prompt="$func: The destination directory...${nl}  ${dir}${nl}...does not exist. Create? (y/n): "
        while [[ -z $response ]]
        do
            readcmd "$prompt" response
            case $response in
                y|Y) response="Y" ;;
                n|N) ;;
                *) response=
                   prompt="$func: Invalid response.${nl}  Create destination directory? (y/n): ";;
            esac
        done
        if [[ $response == "Y" ]]
        then
            $DEBUG mkdir -p "$dir" && $DEBUG cp -i "$1" "$2"
        else
            echo "$func: Cancelled." >&2
        fi
    fi
}

다른 팁

는 오류 메시지가 오고서 cp 명령하지 않 zsh.을 개선하려는 경우,출력을 가을 쓰기에 대한 논리를 잘라내고 검토하는 경로를 따라로 확인하면 그것은 존재하지 않습니다.

있는 명령을 지원하는 이 보 basename(1)dirname(1).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top