Tuesday, November 22, 2011

shell script Part4. file handling


Utility small scripts.

Reading directories using wildcards

  for file in /home/user/*
  do
    if [ -d "$file" ]
    then
      echo "$file is a directory"
    elif [ -f "$file" ]
    then
      echo "$file is a file"
    else
      echo "$file is neither a file nor a directory"
    fi
  done

  Observe that in the checks $file is enclosed in double quotes since the names can also contain spaces and in that case we would want the whole name to be treated as one element for the FOR loop.

Reading and displaying the contents of the passwd file in some meaningful format.

Now the passwd file contains lines of records in the following format, denoting the information about each of the users(both visible and system)

login_name:password:user_id:group_id:description_of_account:HOME_directory_location:default_shell_for_user

We would like to present each user's information in a tree-like structure, that makes things more readable. Yes, you can write them to a file for future readability.

  IFS=$'\n'
  for line in `cat /etc/passwd`
  do
    echo "Values: $line"
    IFS=:
    for field in $line
    do
      echo "  Field: $field"
    done
  done

No comments:

Post a Comment