chop
chop

Reputation: 471

How do I run a command in a list of directories using bash?

I need to run some commands in OS X User directories, apart from "Shared" and our local admin account. So far, I have:

#!/bin/bash
userFolders=$(find /Users/ -type d -depth 1 | sed -e 's/\/\//\//g' | egrep -v "support|Shared")
for PERSON in "$userFolders"; do
    mkdir $PERSON/Desktop/flagFolderForLoop
done

Running the above as root, I get

mkdir: /Users/mactest1: File exists

Where might I be going wrong?

Upvotes: 0

Views: 175

Answers (2)

hagu
hagu

Reputation: 1

Instead of find you can use dscl to list (regular, standard) /Users on Mac OS X.

dscl . -list  /Users NFSHomeDirectory

# list name of users
dscl . -list /Users NFSHomeDirectory | 
   awk '/^[^[:space:]]+[[:space:]]+\/Users\//{print $1}'

# list home directories of users
dscl . -list /Users NFSHomeDirectory | 
   awk '/^[^[:space:]]+[[:space:]]+\/Users\//{$1=""; sub(/^ */,""); print $0}'

Upvotes: 0

dogbane
dogbane

Reputation: 274720

You should remove the quotes around "$userFolders" so that your loop iterates over each person correctly.

The following example illustrates the difference between quoting and not quoting:

With quotes:

for i in "a b c"
do
    echo "Param: $i"
done

prints only one parameter:

Param: a b c

Without quotes:

for i in a b c
do
    echo "Param: $i"
done

prints each parameter:

Param: a
Param: b
Param: c

Also, you can tell find to exclude certain directories, like this:

for PERSON in $(find /Users/ -type d -depth 1 ! -name support ! -name Shared)
do
    mkdir "$PERSON"/Desktop/flagFolderForLoop
done

Upvotes: 1

Related Questions