display how many files that user accessed

All of these commands can be used inside of your scripts and can make for a very powerful toolset for developing programs in unix. For an example of using these commands in a script, let’s write a script that uses our current data file. The script will get all users that are in the file and will then display how many files that user accessed. We will also have the script get all files in the file and display how many times each file was accessed. There are much more efficient ways of doing these specific functions, but for this example we will do it to better show how you can use these commands in a script.

#!/bin/sh

# First let's get the list of unique users:
USERS=`awk '{print $1}' testfile | sort -u`

echo "Users:"

# Now loop through each user.
for USER in $USERS
do
	# Get the number of lines that start with the user name.
	NUM=`grep -c "^$USER" testfile`

	echo " - $USER: $NUM files accessed."
done

# Now let's get the list of unique files:
FILES=`awk '{print $4}' testfile | sort -u`

echo ""
echo "Files:"

# And loop through each file.
for FILE in $FILES
do
	# Get the number of lines that end with the file name.
	NUM=`grep -c "$FILE$" testfile`

	echo " - $FILE: $NUM accesses."
done

Notice that we use the command line parameter -c for grep, this returns a row count instead of a list of rows. Another thing to notice is that we are reading the whole file 2 + (num_users * 2) times. In our case, that’s 8 times. A smarter program would be able to read the file once and get the data it needs to parse out, because I/O calls on a system (such as reading a file) are always slower than reading from memory (variables).

Now let’s save the script as test.sh and run it. We get the following output:

$ ./test.sh
Users:
- root: 4 files accessed.
- user1: 3 files accessed.
- user2: 3 files accessed.

Files:
- /usr/local/bin/one_app: 2 accesses.
- /usr/local/bin/two_app: 3 accesses.
- /usr/local/src/file.c: 1 accesses.
- /var/logs/approot.log: 2 accesses.
- /var/logs/system.log: 2 accesses.

source: www. dreamsyssoft.com/sp_ss.jsp

Tags: , , , , , , , , , , , , , ,