-1

I have an idea, how to check availability of "id_rsa.pub" for each user in home directory. But something does not work. My script:

#!/bin/bash

users=`ls /home/`

for i in "$users"; do
if [[ -f "/home/$i/.ssh/id_rsa.pub" ]]; then
    echo "All users have this key"
else
    echo "Users $i don't have this key, We need build key for this users"
fi
done

In the debug:

+ [[ -f /home/donovan
valeri
john
roman
colbi
testuser/.ssh/id_rsa.pub ]]

How i see, it takes a full path, but don't full path for each user. Please help, what i do wrong ? Thanks for your attention. And of course, i have a result:

Users donovan
valeri
john
roman
colbi
testuser don't have this key, We need build key for this users
Piduna
  • 1
  • 3

2 Answers2

1

The quotes are causing all usernames to be seen as a single string:

for i in "$users"; do

Remove the quotes and it works:

for i in $users; do

Usernames don't contain spaces, so you should be safe here.

Gerald Schneider
  • 23,274
  • 8
  • 57
  • 89
1

The ls /home is not a good idea to use in scripts. ls is a human-readable listing command and not meant to be used in scripts.

You can simply create an array and loop through the indices e.g

#!/usr/bin/env bash

users=(/home/*)

for i in "${users[@]}"; do
if [[ -f "$i/.ssh/id_rsa.pub" ]]; then
    echo "All users have this key"
else
    echo "Users $i don't have this key, We need build key for this users"
fi
done
Valentin Bajrami
  • 4,045
  • 1
  • 18
  • 26
  • I'd go one further and validate that they are actually users like `users=( $(getent passwd | awk -F: '($3 >= 1000 && $3 <= 65000){print $6}') )` – Andrew Domaszek Mar 30 '17 at 10:39