2009-12-01 7 views
2

배열의 값을 변경하고 싶습니다. 어떤 도움을 주셔서 감사합니다.Bash : 배열을 어떻게 자릅니다?

내가 가지고 같은 배열 : 나는 사용자가 존재하는지 테스트 할 수하고 싶습니다

users=(root isometric akau) 

을 (이것은 실제로 현재 사용자의 목록입니다) 그들이하지, 그 다음에 할 경우 배열에서 사람을 제거하십시오. 내가 for 루프에 넣어 그것을 평가하여이 실험을 시도했다 :

for i in ${users[@]}; do 
    eval "users=($([ -z $(grep \"^\$i\" /etc/shadow) ] && sed \"s/\$i//g\"))" 
done 

echo $users 

나는 내가 할 수있는 확실하지 않다 (I 좀 더이 가지고 노는 생각하지만 난 너무 복잡 받고있을 줄 알았는데 배열에 명령 넣기). 누구든지이 작업을 수행하는 방법에 대해 알고 있습니까?

편집 :

cnt=0 
for i in ${users[@]}; do 
    [ -z "$(grep "^$i" /etc/shadow)" ] && unset users[cnt] || ((cnt++)) 
done 

Edit2가 :

가 실제로 데니스의 더 나은입니다 내가 배열 변수가 설정되지 않은 번호를 입력하는 방법

.

답변

5

당신을 for 루프가 필요하지 않을 수 있습니다. 이 시도 :

users=(root isometric akau) 
list="${users[@]/%/|}"  # convert array to list, add pipe char after each user 
# strip the spaces from the list and look for usernames between the beg. of the line 
# and the end of the word, make an array out of the result 
users=($(grep -Eo "^(${list// })\>" /etc/shadow)) 

grep, 풀어, 다음과 같을 것이다 :

grep -Eo "^(root|isometric|akau|)\>" /etc/shadow 
+0

매우 똑똑합니다. 가능하다면 독창성에 2를 더한 것입니다. 고맙습니다. –

+0

더 자세히 보니 정말 좋습니다. 와우 –

0

당신은 users에서 jane을 제거하려면 :

users=(john joe mary jane liz root foobar) 

for ((i = 0; i < ${#users[@]}; ++i)); do 
    [[ ${users[i]} == jane ]] && break 
done 

users=(${users[@]:0:i} ${users[@]:i+1}) 

echo "${users[@]}" #=> john joe mary liz root foobar 

일반적인 원칙은 bash는 (분명히)에는 배열 슬라이스가 없다는 것입니다; 제외 된 요소없이 배열을 다시 만들어야합니다.

그렇다면 for (in) 루프에서 찾고있는 것을 수행하는 방법은 다양합니다. 당신이 그렇다면

3

...

$ users=(root isometric akau) 
$ echo ${users[*]} 
root isometric akau 

당신이해야 할 모든이는 말 : 다음

$ unset users[1] 

그리고 ...

$ echo ${users[*]} 
root akau 
$ 
+0

하하, 좋은. 훨씬 낫다. DR 감사합니다. 참고로, 원래 게시물의 배열 값의 수를 찾는 방법을 설명합니다. –

0
users=(root nobody akau) 
declare -a shadowusers 
declare -a notinshadow 
i=0 
while IFS=":" read -r user b c d e f g h 
do 
    shadowusers[$i]=$user 
    i=$((i+1)) 
done < "/etc/shadow" 
for u in ${users[@]} 
do 
    found=0 
    for s in ${shadowusers[@]} 
    do 
      case "$u" in 
       "$s") found=1;; 
      esac 
    done 
    [ "$found" -eq 0 ] && notinshadow[$j]=$u 
    j=$((j+1)) 
done 
echo ${notinshadow[@]} 
+0

+1 독창성. 결코 전에 루프로 리디렉션 생각 ... 허. –

관련 문제