2017-09-25 14 views
1

타 기능의 함수 (문자열 PARAM가) 사용 방법 : 윈 기능을 시험하기 전에배쉬 : 내 .bashrc에 이러한 기능을 가지고

# This function just untar a file: 
untar() 
{ 
    tar xvf $1 
} 

# This function execute a command with nohup (you can leave the terminal) and nice for a low priority on the cpu: 
nn() 
{ 
    nohup nice -n 15 "[email protected]" & 
} 

, 나는 타르를 만들 :

nn untar test.txt.tar 

만이 작동합니다 :

echo test > test.txt 
tar cvf test.txt.tar test.txt 

지금 제가하고 싶은 것은

nohup.out은에서 여기
nn tar xvf test.txt.tar 

오류 :

nice: ‘untar’: No such file or directory 

답변

2

기능하지 일류 시민입니다. 셸은 그 내용을 알고 있지만 find, xargsnice과 같은 다른 명령은 알지 못합니다. 다른 프로그램에서 함수를 호출하려면 (a) 하위 쉘로 함수를 내보내고 (b) 명시 적으로 하위 쉘을 호출해야합니다.

export -f untar 
nn bash -c 'untar test.txt.tar' 

당신은 호출자의 경우 더 쉽게하려는 경우이 작업을 자동화 할 수 있습니다 :

set -- bash -c '"[email protected]"' bash "[email protected]" 
  1. set -- 현재 함수의 인수를 변경 :이 줄은 설명을받을 권리가

    nn() { 
        if [[ $(type -t "$1") == function ]]; then 
         export -f "$1" 
         set -- bash -c '"[email protected]"' bash "[email protected]" 
        fi 
    
        nohup nice -n 15 "[email protected]" & 
    } 
    

    ; "[email protected]"을 새 값 세트로 바꿉니다.

  2. bash -c '"[email protected]"'은 명시 적 서브 쉘 호출입니다.
  3. bash "[email protected]"은 서브 쉘에 대한 인수입니다. bash$0 (사용되지 않음)입니다. 기존의 외부 인수 인 "[email protected]"은 새로운 bash 인스턴스로 $1, $2 등으로 전달됩니다. 이것은 함수 호출을 수행하는 서브 쉘을 얻는 방법입니다.

nn untar test.txt.tar으로 전화하면 어떻게되는지 봅시다. type -t 검사는 untar이 함수임을 확인합니다. 함수가 내보내집니다. 그런 다음 setnn의 인수를 untar test.txt.tar에서 bash -c '"[email protected]"' bash untar test.txt.tar으로 변경합니다.