Skip to main content

Posts

Showing posts from July, 2011

"IF" statement test condtions in Shell Script

Following are some "IF" Statement constructs to test conditions provided by the shell:
-b file = True if the file exists and is block special file. -c file = True if the file exists and is character special file. -d file = True if the file exists and is a directory. -e file = True if the file exists. -f file = True if the file exists and is a regular file -g file = True if the file exists and the set-group-id bit is set. -k file = True if the files' "sticky" bit is set. -L file = True if the file exists and is a symbolic link. -p file = True if the file exists and is a named pipe. -r file = True if the file exists and is readable. -s file = True if the file exists and its size is greater than zero. -s file = True if the file exists and is a socket. -t fd = True if the file descriptor is opened on a terminal. -u file = True if the file exists and its set-user-id bit is set. -w file = True if the file exists and is writable. -x file = True if the file exists and …

'Type' example in Shell Script

Here we are calling functions directly using 'type' after parsing them in SUB_CMD through command line:

##############################################
PROG_NAME="$(basename $0)"
SUB_CMD="$1"
retval=0
if [ "$(type -t "${SUB_CMD}")" == 'function' ] ; then
    ${SUB_CMD}
    retval=$?
else
    echo "Invalid command '${SUB_CMD}'"
    usage
    retval=1
fi
exit ${retval}
##############################################

Spiral Traversal of Matrix

#include <iostream>
using namespace std;

int mat[4][3] = {{1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}};

void print_spiral(int mat[4][3], int m, int n, int k) {
  if (m <= 0 || n <= 0)
    return;
  if (m == 1) {
    for (int j = 0; j < n; j++)
      cout << mat[k][k+j] << " ";
    return;
  }
  if (n == 1) {
    for (int i = 0; i < m; i++)
      cout << mat[k+i][k] << " ";
    return;
  }
  // print from top left
  for (int j = 0; j < n - 1; j++)
    cout << mat[k][k+j] << " ";
  // print from top right
  for (int i = 0; i < m - 1; i++)
    cout << mat[k+i][k+n-1] << " ";
  // print from bottom right
  for (int j = 0; j < n - 1; j++)
    cout << mat[k+m-1][k+n-1-j] << " ";
  // print from bottom left
  for (int i = 0; i < m - 1; i++)
    cout << mat[k+m-1-i][k] << " ";

  print_spiral(mat, m-2, n-2, k+1);
}

int main()
{
    int m = …