별칭 명령에서 정규식을 사용할 수 있습니까? 만들고 싶습니다.

이 명령의 별칭을 만들고 싶습니다. ssh user @ ip를

 alias [0-9][0-9][0-9].[0-9][0-9][0-9].[0-9][0-9][0-9].[0-9][0-9][0-9] ="ssh user@$0"

나는 그것을 만들었지 만 작동하지 않습니다. 이 명령에 구문 오류가 있습니까?



답변

별칭 명령에는 정규식을 사용할 수 없습니다.

원하는 것을 달성하기 위해 Bash에서을 사용할 수 있습니다 command_not_found_handle. 로부터 참조 설명서 :

이름이 쉘 함수도 아니고 내장도 아니며 슬래시를 포함하지 않으면 Bash $PATH는 해당 이름으로 실행 파일을 포함하는 디렉토리를 각 요소에서 검색합니다 . Bash는 해시 테이블을 사용하여 여러 PATH검색 을 피하기 위해 실행 파일의 전체 경로 이름을 기억합니다 (Bourne Shell Builtins의 해시 설명 참조). 디렉토리의 전체 검색은 $PATH명령이 해시 테이블에없는 경우에만 수행됩니다. 검색에 실패하면 쉘은 이름이 지정된 정의 된 쉘 함수를 검색합니다.command_not_found_handle. 해당 함수가 존재하면 원래 명령과 원래 명령의 인수를 인수로 사용하여 호출되며 함수의 종료 상태는 쉘의 종료 상태가됩니다. 해당 함수가 정의되어 있지 않으면 쉘은 오류 메시지를 인쇄하고 종료 상태 127을 리턴합니다.

그런 다음 다음과 같은 작업을 수행 할 수 있습니다.

command_not_found_handle() {
    local i ip ip_ok=0
    if [[ $1 = +([[:digit:]]).+([[:digit:]]).+([[:digit:]]).+([[:digit:]]) ]]; then
        IFS=. read -a ip <<< "$1"
        ip_ok=1
        for i in "${ip[@]}"; do
            [[ $i = $((10#$i)) ]] && (( i>=0 && i<=255 )) || { ip_ok=0; break; }
        done
    fi
    if ((ip_ok)); then
        ssh "user@$1"
    else
        ( unset -f command_not_found_handle; "$@" )
    fi
}

command_not_found_handle예를 들어 우분투와 같이 이미 정의 된 환경에 있다면

The program 'whatever' can be found in the following packages:
 * whatever
 * whatever-ever
Try: sudo apt-get install <selected package>

이것을 무시하고 싶지 않을 것입니다. 함수를 다음과 같이 원숭이 패치 할 수 있습니다 ( .bashrc).

# Guard to not monkey-patch twice, in case this file is sourced several times
if ! declare -f kalai_command_not_found_existent &>/dev/null; then
    mapfile -s1 -t kalai_command_not_found_existent_ary < <(declare -f command_not_found_handle 2>/dev/null)
    if ((${#kalai_command_not_found_existent_ary[@]})); then
        eval "$(printf '%s\n' "kalai_command_not_found_existent ()" "${kalai_command_not_found_existent_ary[@]}")"
    else
        kalai_command_not_found_existent() { ( unset -f command_not_found_handle; "$@" ) }
    fi
    command_not_found_handle() {
        local i ip ip_ok=0
        if [[ $1 = +([[:digit:]]).+([[:digit:]]).+([[:digit:]]).+([[:digit:]]) ]]; then
            IFS=. read -a ip <<< "$1"
            ip_ok=1
            for i in "${ip[@]}"; do
                [[ $i = $((10#$i)) ]] && (( i>=0 && i<=255 )) || { ip_ok=0; break; }
            done
        fi
        if ((ip_ok)); then
            ssh "user@$1"
        else
            kalai_command_not_found_existent "$@"
        fi
    }
    unset command_not_found_existent_ary
fi

답변

아니요, 그런 식으로 사용할 수 없습니다.

별명을 사용하면 명령을 입력 할 때 명령을 정렬 할 수 있습니다. 예를 들면 다음과 같습니다.

alias ls="ls -lh"

입력 할 때 ls시스템은 원하는 말을 알고 있습니다 ls -lh.

귀하의 경우 ssh user@서버 이름 만 입력하려면 다음과 같이 선언하는 것이 좋습니다.

alias myssh="ssh -l user"

그렇다면 myssh server당신이 실제로하고있는 일은입니다 ssh -l user server.