bash 배열이 이상하게 동작합니다

bash 배열이 이상하게 동작합니다

/tmp 아래에 두 개의 폴더가 있습니다.

터미널에서 출발:

ls -d /tmp/firefox-*

/tmp/firefox-sy2vakcj.default-esr-charlie-cache
/tmp/firefox-sy2vakcj.default-esr-charlie-profile

또는

compgen -G /tmp/firefox-*

/tmp/firefox-sy2vakcj.default-esr-charlie-cache
/tmp/firefox-sy2vakcj.default-esr-charlie-profile

출력을 배열에 저장할 수도 있습니다.

arr=( $(ls -d /tmp/firefox-*) )
echo $arr
tmp/firefox-sy2vakcj.default-esr-charlie-cache  /tmp/firefox-sy2vakcj.default-esr-charlie-profile
 
echo $arr[1] 
tmp/firefox-sy2vakcj.default-esr-charlie-cache

echo $arr[2]
/tmp/firefox-sy2vakcj.default-esr-charlie-profile

여태까지는 그런대로 잘됐다.

하지만 스크립트에서 동일한 작업을 수행하려고 하면 다음과 같습니다.

    ...
    ... 
    arr=( "$(ls -d /tmp/firefox-*)" ) ||( echo "directory doesn't exist" && exit 1)
    #arr=( "$(compgen -G /tmp/firefox-*)" ) ||( echo "directory doesn't exist" && exit 1)
    echo "this is a test for arr[1]: $arr[1]"
    echo "this is a test for arr[2]: $arr[2]"
    ...
 

나는 출력을 얻습니다 :

스크립트에서:

ls -d출력은 다음과 같습니다 .

+ arr=("$(ls -d /tmp/firefox-*)")
++ ls -d '/tmp/firefox-*'
ls: cannot access '/tmp/firefox-*': No such file or directory
+ echo 'directory doesn'\''t exist'
directory doesn't exist

의 경우 compgen -G출력은 다음과 같습니다.

this is a test for arr[1]: /tmp/firefox-sy2vakcj.default-esr-charlie-cache
/tmp/firefox-sy2vakcj.default-esr-charlie-profile[1]
this is a test for arr[2]: /tmp/firefox-sy2vakcj.default-esr-charlie-cache
/tmp/firefox-sy2vakcj.default-esr-charlie-profile[2]

내 질문:

1.명령의 하위 쉘에서 glob이 확장되지 않는 이유는 무엇입니까 ls -d?

2.의 경우 compgen -G값은 배열에 어떻게 저장됩니까? 출력은 배열의 각 항목이 디렉터리 항목을 저장하고 두 번째 디렉터리 항목을 자체 인덱스 배열로 저장하는 것처럼 보입니까?

삼.이 두 명령의 터미널 출력이 스크립트와 다른가요, 아니면 뭔가 빠졌나요?

답변1

  1. ls -d 명령의 하위 쉘에서 glob이 확장되지 않는 이유는 무엇입니까?

닫힌 와일드카드를 사용했을 수도 있습니다 set -f. 전시하다:

$ touch firefox-1 firefox-2
$ arr=( firefox-* ); declare -p arr
declare -a arr=([0]="firefox-1" [1]="firefox-2")
$ set -f
$ arr=( firefox-* ); declare -p arr
declare -a arr=([0]="firefox-*")
  1. compgen -G를 사용하면 값이 배열에 어떻게 저장되나요? 출력은 배열의 각 항목이 디렉터리 항목을 저장하고 두 번째 디렉터리 항목을 자체 인덱스 배열로 저장하는 것처럼 보입니까?

이렇게 하면 arr=( "$(compgen -G /tmp/firefox-*)" )큰따옴표로 인해 compgen 출력이 다음과 같이 저장됩니다.단일 요소배열에서. 이 경우 다음을 읽으십시오.출력 라인 수mapfile프로세스 대체에 사용하기 위해 배열에 넣습니다 .

$ mapfile -t arr < <(compgen -G ./firefox-*)
$ declare -p arr
declare -a arr=([0]="./firefox-1" [1]="./firefox-2")
  1. 이 두 명령의 터미널 출력이 스크립트와 다른가요, 아니면 뭔가 빠졌나요?

대화형 쉘이 zsh인 것 같습니다. 그 외에도 중괄호가 필요한 배열 요소에 대한 매개변수 확장 구문이 누락되었습니다(3.5.3 쉘 매개변수 확장), bash 배열은 0부터 인덱싱됩니다.

echo "${arr[0]}"

관련 정보