Skip to main content
1 of 2
Gao
  • 1.1k
  • 8
  • 21

Just don't create that many subprocesses. Your objective is to prepare a string of INSERT statements and feed it to one invocation of sqlite3. So drop the whole while read block and do the text manipulation on your users variable.

#!/bin/sh
db='./users.db'
insert_users=$(
    getent passwd 'joe' 'bill' 'tom' | awk -F':' -v quote="'" -v OFS="', '"\
    '{print "INSERT INTO Users VALUES ("quote $3, $4, $1, $6 quote");"}'
)
sqlite3 "$db" <<EOF
DROP TABLE Users;
CREATE TABLE Users \
    (UID INTEGER PRIMARY KEY, GID INTEGER, Username TEXT, Home TEXT);
$insert_users
EOF

Doing a grep on /etc/passwd has a few drawbacks: the passwd file might not be located in /etc (I don't know of any Unix-like OS for which this is true, though), and it won't have the users that are stored in LDAP/NIS, etc. On the other hand, some systems don't have getent, so this method is not perfect, either. You might want to fall back to grep if getent returns a "command not found".

Gao
  • 1.1k
  • 8
  • 21