내 쉘 스크립트 이해하기 [닫기]

내 쉘 스크립트 이해하기 [닫기]

bash에서 디렉터리를 자동으로 마운트하고 ~/tmp디렉터리가 없으면 디렉터리를 생성하는 데 사용하는 함수를 작성했습니다.

# mkdir & mount auto
mnt() {
    dir="$1";
    mkdir ~/tmp/$dir;
    /usr/bin/sudo mount /dev/$dir ~/tmp/$dir;
    cd ~/tmp/$dir;
}

몇 가지 문제...

dir="$1";

변수 dir을 mnt 이후의 입력으로 설정합니다
. 이 변수 $1를 래핑해야 하며 ""각 줄 뒤에는 a가 있어야 합니까? ;그렇지 않다면 작동할까요 ;?

/usr/bin/sudo mount /dev/$dir ~/tmp/$dir;

유튜브 영상을 봤어요Bash의 $PATH에 대해 알아야 할 모든 것

스크립트에는 전체 경로를 작성해야 합니다...

/usr/bin/sudo 

대신에...

sudo

그 이유는 무엇입니까?

답변1

이 기능의 더 나은 버전:

mnt() {
  typeset dir # for local scope for the variable.
              # assumes ksh88/pdksh/bash/zsh/yash. Replace typeset with
              # local for ash-based shells (or pdksh/bash/zsh)

  dir=$1 # here it's the only place where you don't need the quotes
         # though they wouldn't harm

  mkdir -p -- ~/tmp/"$dir" || return
     # quotes needed. mkdir -p creates intermediary directories as required
     # and more importantly here, doesn't fail if the directory already
     # existed.
     # We return from the function if mkdir failed (with the exit status
     # of mkdir). The -- is for the very unlikely even that your $HOME starts
     # with "-". So you may say it's a pedantic usage here. But it's good
     # habit to use it when passing an arbitrary (not known in advance)
     # argument to a command.

  sudo mount "/dev/$dir" ~/tmp/"$dir" || return
     # Or use /usr/bin/sudo if there are more than one sudo commands in $PATH
     # and you want to use the one in /usr/bin over other ones.
     # If you wanted to avoid calling an eventual "sudo" function  or alias 
     # defined earlier in the script or in a shell customisation file, 
     # you'd use "command sudo" instead.

  cd -P -- ~/tmp/"$dir" # another pedantic use of -P for the case where
                        # your $HOME contains symlinks and ".." components
}

세미콜론은 필요하지 않습니다. 쉘 프롬프트에서 다음과 같이 작성할 수 있습니다.

cd /some/where
ls

아니요

cd /some/where;
ls;

이는 스크립트에서도 다르지 않습니다. ;다음을 사용하여 한 줄에서 명령을 구분할 수 있습니다 .

cd /some/where; ls

그러나 다음과 같이 작성하는 것이 좋습니다.

cd /some/where && ls

ls무조건 실행 되는 것이 아니라 , cd성공할 경우에만 실행됩니다.

답변2

질문:

  • $1을 ""로 묶어야 합니까?

    짧은 대답은 '예'입니다

더 읽어보기

  • 각 줄 뒤에 ;가 있어야 합니까? ; 없이 작동합니까?

    ;명령 구분 기호로, 여러 명령이 같은 줄에 있는 경우에만 필요합니다(예: ) echo "Hello, World"; echo. 명령이 별도의 줄(예: 스크립트)에 있는 경우에는 필요하지 않지만 아무 것도 중단하지 않습니다.

  • 명령 이름만 지정하는 대신 전체 경로를 지정해야 하는 이유는 무엇입니까?

    명령 이름만 입력하면 해당 명령이 처음 나타나는 경로가 분석됩니다. 특히 GNU 도구와 동일한 명령의 다른 변형이 존재하는 경우 다양한 위치에서 여러 명령을 사용하는 것은 드문 일이 아닙니다. 사용 중인 명령의 전체 경로를 지정하지 않으면 쉘에서 사용할 명령을 결정하지만 실제로 원하는 것이 아닐 수도 있습니다.

나는 약간 동의하지 않는다언제나내 경험상 일반적으로 필요하지 않고 특정 버전의 도구를 찾는 데에만 관심이 있으므로 전체 경로를 지정하십시오. 예외도 있지만 고려하기 전에 더 잘 이해해야 한다고 생각합니다. 예를 들어, 내 환경에서 대부분의 Unix 컴퓨터는 기본적으로 GNU 도구를 사용하지 않지만 많은 도구가 컴퓨터에 설치되어 있으므로 해당 컴퓨터 중 하나에 대해 GNU 버전 도구를 사용해야 하는 경우 해당 도구의 전체 경로를 지정해야 합니다.


mnt() {
    dir="$1";                                   # Sets the value of dir to your first positional parameter
    mkdir ~/tmp/$dir;                           # Creates your a directory named after the value of $dir in $HOME/tmp/
    /usr/bin/sudo mount /dev/$dir ~/tmp/$dir;   # Mounts the device in /dev/$dir to your newly created folder (You better hope you set $1 properly)
    cd ~/tmp/$dir;                              # changes to your newly created/mounted directory.
}

관련 정보