Archive

Posts Tagged ‘Linux Command’

Howto uncompress .txz and .xz files in Linux

February 4th, 2010 Jimmy No comments

TXZ compression seems to be starting to take off in the Linux community. Slackware 13.0 is a Linux distribution that is  activley using XZ compression. Slackware used to use gzip and the .tgz extension was used. Now that XZ compression is used the new Slackware packages use the .txz extension. In order to uncompress .TXZ or .XZ files you will need to install the xz-utils package from your package manager or download and compile your own version from source code.

Uncompress Usage:xz -d glibc-solibs-2.9-i486-3.txz
Compress Usage: xz -c myxzfile.xz mybigfile.tar

Source code download

Categories: Power Computing Tags: ,

Linux: cal – display a calendar

February 2nd, 2010 Jimmy No comments

cal

Display a calendar

Syntax
      cal [-mjy] [[month] year]

Options:

     -m      Display monday as the first day of the week.

     -j      Display julian dates (days one-based, numbered from January 1).

     -y      Display a calendar for the current year.

    A single parameter specifies the 4 digit year (1 - 9999) to be displayed.

    Two parameters denote the Month (1 - 12) and Year (1 - 9999).

    If arguments are not specified, the current month is displayed.

    A year starts on 01 Jan.
Categories: Power Computing Tags:

Linux: (g) awk – search and replace.

January 29th, 2010 Jimmy No comments

awk or gawk (gnu awk)

Find and Replace text, database sort/validate/index

Syntax

      awk <options> 'Program' Input-File1 Input-File2 ...

      awk -f PROGRAM-FILE <options> Input-File1 Input-File2 ...

Key
 -F FS
 --field-separator FS
     Use FS for the input field separator (the value of the `FS'
     predefined variable).

 -f PROGRAM-FILE
 --file PROGRAM-FILE
     Read the `awk' program source from the file PROGRAM-FILE, instead
     of from the first command line argument.

 -mf NNN
 -mr NNN
     The `f' flag sets the maximum number of fields, and the `r' flag
     sets the maximum record size.  These options are ignored by
     `gawk', since `gawk' has no predefined limits; they are only for
     compatibility with the Bell Labs research version of Unix `awk'.

 -v VAR=VAL
 --assign VAR=VAL
     Assign the variable VAR the value VAL before program execution
     begins.

 -W traditional
 -W compat
 --traditional
 --compat
     Use compatibility mode, in which `gawk' extensions are turned off.

 -W lint
 --lint
     Give warnings about dubious or non-portable `awk' constructs.

 -W lint-old
 --lint-old
     Warn about constructs that are not available in the original
     Version 7 Unix version of `awk'.

 -W posix
 --posix
     Use POSIX compatibility mode, in which `gawk' extensions are
     turned off and additional restrictions apply.

 -W re-interval
 --re-interval
     Allow interval expressions, in regexps.

 -W source=PROGRAM-TEXT
 --source PROGRAM-TEXT
     Use PROGRAM-TEXT as `awk' program source code.  This option allows
     mixing command line source code with source code from files, and is
     particularly useful for mixing command line programs with library
     functions.

 --
     Signal the end of options.  This is useful to allow further
     arguments to the `awk' program itself to start with a `-'.  This
     is mainly for consistency with POSIX argument parsing conventions.

'Program'
     A series of patterns and actions: see below

Input-File
     If no Input-File is specified then `awk' applies the Program to
     "standard input", (piped output of some other command or the terminal.
     Typed input will continue until end-of-file (typing `Control-d')

Basic functions

The basic function of awk is to search files for lines (or other units of text) that contain a pattern. When a line matches, awk performs a specific action on that line.

The Program statement that tells `awk’ what to do; consists of a series of “rules”. Each rule specifies one pattern to search for, and one action to perform when that pattern is found.

For ease of reading, each line in an `awk’ program is normally a separate Program statement , like this:

     pattern { action }
     pattern { action }
     ...

e.g. Display lines from my_file containing the string “123″ or “abc” or “some text”:

awk '/123/ { print $0 }
     /abc/ { print $0 }
     /some text/ { print $0 }' my_file

A regular expression enclosed in slashes (`/’) is an `awk’ pattern that matches every input record whose text belongs to that set. e.g. the pattern /foo/ matches any input record containing the three characters `foo’, *anywhere* in the record.

`awk’ patterns may be one of the following:

/Regular Expression/        - Match =
Pattern && Pattern          - AND
Pattern || Pattern          - OR
! Pattern                   - NOT
Pattern ? Pattern : Pattern - If, Then, Else
Pattern1, Pattern2          - Range Start - end
BEGIN                       - Perform action BEFORE input file is read
END                         - Perform action AFTER input file is read

In addition to simple pattern matching `awk’ has a huge range of text and arithmetic Functions, Variables and Operators.

`gawk’ will ignore newlines after any of the following:

    , { ? : || && do else

Comments – start with a `#’, and continue to the end of the line:

 # This program prints a nice friendly message

Examples

This program prints the length of the longest input line:

 awk '{ if (length($0) > max) max = length($0) }
      END { print max }' data

This program prints every line that has at least one field. This is an easy way to delete blank lines from a file (or rather, to
create a new file similar to the old file but from which the blank lines have been deleted)

 awk 'NF > 0' data

This program prints seven random numbers from zero to 100, inclusive.

 awk 'BEGIN { for (i = 1; i <= 7; i++)
                print int(101 * rand()) }'

This program prints the total number of bytes used by FILES.

 ls -lg FILES | awk '{ x += $5 } ; END { print "total bytes: " x }'

This program prints a sorted list of the login names of all users.

 awk -F: '{ print $1 }' /etc/passwd | sort

This program counts lines in a file.

 awk 'END { print NR }' data

This program prints the even numbered lines in the data file. If you were to use the expression `NR % 2 == 1′ instead, it would print the odd numbered lines.

 awk 'NR % 2 == 0' data
Categories: Power Computing Tags:

Linux: cut – divide file into columns.

January 28th, 2010 Jimmy No comments

cut

Divide a file into several parts (columns)
Writes to standard output selected parts of each line of each input file, or standard input if no files are given or for a file name of `-’.

Syntax
     cut [OPTION]... [FILE]...

In the options below, BYTE-LIST, CHARACTER-LIST, and FIELD-LIST are one or more numbers or ranges (two numbers separated by a dash)

Bytes, characters, and fields are are numbered starting at 1 and separated by commas.
Incomplete ranges may be given: -M means 1-M  ;  N- means N through end of line or last field.

Options

-b BYTE-LIST
--bytes=BYTE-LIST
     Print only the bytes in positions listed in BYTE-LIST.  Tabs and
     backspaces are treated like any other character; they take up 1
     byte.

-c CHARACTER-LIST
--characters=CHARACTER-LIST
     Print only characters in positions listed in CHARACTER-LIST.  The
     same as `-b' for now, but internationalization will change that.
     Tabs and backspaces are treated like any other character; they
     take up 1 character.

-f FIELD-LIST
--fields=FIELD-LIST
     Print only the fields listed in FIELD-LIST.  Fields are separated
     by a TAB character by default.

-d INPUT_DELIM_BYTE
--delimiter=INPUT_DELIM_BYTE
     For `-f', fields are separated in the input by the first character
     in INPUT_DELIM_BYTE (default is TAB).

-n
     Do not split multi-byte characters (no-op for now).

-s
--only-delimited
     For `-f', do not print lines that do not contain the field
     separator character.

--output-delimiter=OUTPUT_DELIM_STRING
     For `-f', output fields are separated by OUTPUT_DELIM_STRING The
     default is to use the input delimiter.

Example

Parse out column 2 from a semicolon (;) delimited file:

$ cat myfile.txt | cut -d \; -f 2 > output.txt

Linux: screen – multiplex terminals

January 27th, 2010 Jimmy No comments

screen

Multiplex a physical terminal between several processes (typically interactive shells).

Syntax:

   Start a screen session:

       screen [ -options ] [ cmd [args] ]

   Resume a detached screen session:

      screen -r [[pid.]tty[.host]]

      screen -r sessionowner/[[pid.]tty[.host]]

Options:

   -A -[r|R]     Adapt all windows to the new display width & height.
   -c file       Read configuration file instead of .screenrc
   -d (-r)       Detach the elsewhere running screen (and reattach here).
   -dmS name     Start as daemon: Screen session in detached mode.
   -D (-r)       Detach and logout remote (and reattach here).
   -D -RR        Do whatever is needed to Reattach a screen session.
   -d -m         Start in "detached" mode. Useful for system startup scripts.
   -D -m         Start in "detached" mode, & don't fork a new process.
   -list         List our SockDir and do nothing else (-ls)
   -r            Reattach to a detached screen process.
   -R            Reattach if possible, otherwise start a new session.
   -t title      Set title. (window's name).
   -U            Tell screen to use UTF-8 encoding.
   -x            Attach to a not detached screen. (Multi display mode).
   -X            Execute cmd as a screen command in the specified session.

Interactive commands:

     Control-a ?    Display brief help
     Control-a "    List all windows for selection
     Control-a '    Prompt for a window name or number to switch to.
     Control-a 0    Select window 0
     Control-a 1    Select window 1
     ...            ...
     Control-a 9    Select window 9
     Control-a A    Accept a title name for the current window.
     Control-a b    Send a break to window
     Control-a c    Create new window running a shell
     Control-a C    Clear the screen
     Control-a d    Detach screen from this terminal.
     Control-a D D  Detach and logout.
     Control-a f    Toggle flow on, off or auto.
     Control-a F    Resize the window to the current region size.
     Control-a h    Write a hardcopy of the current window to file "hardcopy.n"
     Control-a H    Begin/end logging of the current window to file "screenlog.n"
     Control-a i    Show info about this window.
     Control-a k    Kill (Destroy) the current window.
     Control-a l    Fully refresh current window
     Control-a M    Monitor the current window for activity {toggle on/off}
     Control-a n    Switch to the Next window
     Control-a N    Show the Number and Title of window
     Control-a p    Switch to the Previous window
     Control-a q    Send a control-q to the current window(xon)
     Control-a Q    Delete all regions but the current one.(only)
     Control-a r    Toggle the current window's line-wrap setting(wrap)
     Control-a s    Send a control-s to the current window(xoff)
     Control-a w    Show a list of windows (windows)
     Control-a x    Lock this terminal (lockscreen)
     Control-a X    Kill the current region(remove)
     Control-a Z    Reset the virtual terminal to its "power-on" values
     Control-a Control-\    Kill all windows and terminate screen(quit)
     Control-a :    Enter command line mode(colon)
     Control-a [    Enter copy/scrollback mode(copy)
     Control-a ]    Write the contents of the paste buffer to stdin(paste)
     Control-a _    Monitor the current window for inactivity {toggle on/off}
     Control-a *    Show  a listing of all currently attached displays.

When screen is called, it creates a single window with a shell in it (or the specified command) and then gets out of your way so that you can use the program as you normally would.

Then, at any time, you can:

Create new (full-screen) windows with other programs in them (including more shells)

Kill existing windows

View a list of windows

Switch between windows – all windows run their programs completely independent of each other. Programs continue to run when their window is currently not visible and even when the whole screen session is detached from the user’s terminal.

The interactive commands above assume the default key bindings. You can modify screen’s settings by creating a ~/.screenrc file in your home directory. This can change the default keystrokes, bind function keys F11, F12 or even set a load of programs/windows to run as soon as you start screen.

Attaching and Detaching

Once you have screen running, switch to any of the running windows and type Control-a d. this will detach screen from this terminal. Now, go to a different machine, open a shell, ssh to the machine running screen (the one you just detached from), and type: % screen -r

This will reattach to the session. Just like magic, your session is back up and running, just like you never left it.

Exiting screen completely

Screen will exit automatically when all of its windows have been killed.

Close whatever program is running or type `Exit ‘ to exit the shell, and the window that contained it will be killed by screen. (If this window was in the foreground, the display will switch to the previous window)

When none are left, screen exits.

This page is just a summary of the options available, type man screen for more.

Categories: Power Computing Tags:

Linux: chroot – change root directory.

January 27th, 2010 Jimmy No comments

chroot

Run a command with a different root directory.

‘chroot’ runs a command with a specified root directory. On many systems, only the super-user can do this.

SYNTAX
     chroot NEWROOT [COMMAND [ARGS]...]

     chroot OPTION

Ordinarily, filenames are looked up starting at the root of the directory structure, i.e. ‘/’

‘chroot’ changes the root to the directory NEWROOT (which must exist) and then runs COMMAND with optional ARGS.

If COMMAND is not specified, the default is the value of the `SHELL’ environment variable or `/bin/sh’ if not set, invoked with the `-i’ option.

The only options are `–help’ and `–version’

Categories: Power Computing Tags:

Linux: du – Disk Usage

January 27th, 2010 Jimmy No comments

du

Disk Usage – report the amount of disk space used by the specified files and for each subdirectory.

Syntax
      du [options]... [file]...

With no arguments, `du’ reports the disk space for the current directory. Normally the disk space is printed in units of 1024 bytes, but this can be overridden

OPTIONS

`-a'
`--all'
     Show counts for all files, not just directories.

`-b'
`--bytes'
     Print sizes in bytes, overriding the default block size (*note
     Block size::).

`-c'
`--total'
     Print a grand total of all arguments after all arguments have been
     processed.  This can be used to find out the total disk usage of a
     given set of files or directories.

`-D'
`--dereference-args'
     Dereference symbolic links that are command line arguments.  Does
     not affect other symbolic links.  This is helpful for finding out
     the disk usage of directories, such as `/usr/tmp', which are often
     symbolic links.

`-h'
`--human-readable'
     Append a size letter such as `M' for megabytes to each size.
     Powers of 1024 are used, not 1000; `M' stands for 1,048,576 bytes.
     Use the `-H' or `--si' option if you prefer powers of 1000.

`-H'
`--si'
     Append a size letter such as `M' for megabytes to each size.  (SI
     is the International System of Units, which defines these letters
     as prefixes.)  Powers of 1000 are used, not 1024; `M' stands for
     1,000,000 bytes.  Use the `-h' or `--human-readable' option if you
     prefer powers of 1024.

`-k'
`--kilobytes'
     Print sizes in 1024-byte blocks, overriding the default block size
     (*note Block size::).

`-l'
`--count-links'
     Count the size of all files, even if they have appeared already
     (as a hard link).

`-L'
`--dereference'
     Dereference symbolic links (show the disk space used by the file
     or directory that the link points to instead of the space used by
     the link).

`--max-depth=DEPTH'
     Show the total for each directory (and file if -all) that is at
     most MAX_DEPTH levels down from the root of the hierarchy.  The
     root is at level 0, so `du --max-depth=0' is equivalent to `du -s'.

`-m'
`--megabytes'
     Print sizes in megabyte (that is, 1,048,576-byte) blocks.

`-s'
`--summarize'
     Display only a total for each argument.

`-S'
`--separate-dirs'
     Report the size of each directory separately, not including the
     sizes of subdirectories.

`-x'
`--one-file-system'
     Skip directories that are on different filesystems from the one
     that the argument being processed is on.

`--exclude=PAT'
     When recursing, skip subdirectories or files matching PAT.  For
     example, `du --exclude='*.o'' excludes files whose names end in
     `.o'.

`-X FILE'
`--exclude-from=FILE'
     Like `--exclude', except take the patterns to exclude from FILE,
     one per line.  If FILE is `-', take the patterns from standard
     input.

On BSD systems, `du' reports sizes that are half the correct values
for files that are NFS-mounted from HP-UX systems.  On HP-UX systems,
it reports sizes that are twice the correct values for files that are
NFS-mounted from BSD systems.  This is due to a flaw in HP-UX; it also
affects the HP-UX `du' program.

Example

List the total files sizes for everything 1 directory (or less) below the currrent directory ( . )

[simon@testserver]$ du -hc –max-depth=1 .
400M ./data1
1.0G ./data2
1.3G .
1.3G total

“Never go to a doctor whose office plants have died” – Erma Bombeck

Categories: Power Computing Tags:

Linux: adduser

January 27th, 2010 Jimmy No comments

NAME

useradd – Create a new user or update default new user information 

SYNOPSIS

useradd [-c comment] [-d home_dir]
[-e expire_date] [-f inactive_time]
[-g initial_group] [-G group[,...]]
[-m [-k skeleton_dir] | -M] [-n] [-o] [-p passwd] [-r]
[-s shell] [-u uidlogin
useradd -D [-g default_group] [-b default_home]
[-e default_expire_date] [-f default_inactive]
[-s default_shell]

DESCRIPTION

Creating New Users

When invoked without the -D option, the useradd command creates a new user account using the values specified on the command line and the default values from the system. The new user account will be entered into the system files as needed, the home directory will be created, and initial files copied, depending on the command line options. The version provided with Red Hat Linux will create a group for each user added to the system, unless the -n option is given. The options which apply to theuseradd command are:

-c comment
The new user’s password file comment field.
-d home_dir
The new user will be created using home_dir as the value for the user’s login directory. The default is to append the loginname to default_home and use that as the login directory name.
-e expire_date
The date on which the user account will be disabled. The date is specified in the format YYYY-MM-DD.
-f inactive_days
The number of days after a password expires until the account is permanently disabled. A value of 0 disables the account as soon as the password has expired, and a value of -1 disables the feature. The default value is -1.
-g initial_group
The group name or number of the user’s initial login group. The group name must exist. A group number must refer to an already existing group. The default group number is 1 or whatever is specified in /etc/default/useradd.
-G group,[...]
A list of supplementary groups which the user is also a member of. Each group is separated from the next by a comma, with no intervening whitespace. The groups are subject to the same restrictions as the group given with the -g option. The default is for the user to belong only to the initial group.
-m
The user’s home directory will be created if it does not exist. The files contained in skeleton_dir will be copied to the home directory if the -k option is used, otherwise the files contained in /etc/skel will be used instead. Any directories contained inskeleton_dir or /etc/skel will be created in the user’s home directory as well. The -k option is only valid in conjunction with the -m option. The default is to not create the directory and to not copy any files.
-M
The user home directory will not be created, even if the system wide settings from /etc/login.defs is to create home dirs.
-n
A group having the same name as the user being added to the system will be created by default. This option will turn off this Red Hat Linux specific behavior.
-o
Allow create user with duplicate (non-unique) UID.
-p passwd
The encrypted password, as returned by crypt(3). The default is to disable the account.
-r
This flag is used to create a system account. That is, a user with a UID lower than the value of UID_MIN defined in/etc/login.defs and whose password does not expire. Note that useradd will not create a home directory for such an user, regardless of the default setting in /etc/login.defs. You have to specify -m option if you want a home directory for a system account to be created. This is an option added by Red Hat.
-s shell
The name of the user’s login shell. The default is to leave this field blank, which causes the system to select the default login shell.
-u uid
The numerical value of the user’s ID. This value must be unique, unless the -o option is used. The value must be non-negative. The default is to use the smallest ID value greater than 99 and greater than every other user. Values between 0 and 99 are typically reserved for system accounts.

Changing the default values

When invoked with the -D option, useradd will either display the current default values, or update the default values from the command line. The valid options are

-b default_home
The initial path prefix for a new user’s home directory. The user’s name will be affixed to the end of default_home to create the new directory name if the -d option is not used when creating a new account.

-e default_expire_date
The date on which the user account is disabled.
-f default_inactive
The number of days after a password has expired before the account will be disabled.
-g default_group
The group name or ID for a new user’s initial group. The named group must exist, and a numerical group ID must have an existing entry .
-s default_shell
The name of the new user’s login shell. The named program will be used for all future new user accounts.

If no options are specified, useradd displays the current default values. 

NOTES

The system administrator is responsible for placing the default user files in the /etc/skel directory.
This version of useradd was modified by Red Hat to suit Red Hat user/group conventions. 

CAVEATS

You may not add a user to an NIS group. This must be performed on the NIS server. 

FILES

/etc/passwd – user account information
/etc/shadow – secure user account information
/etc/group – group information
/etc/gshadow – secure group information
/etc/default/useradd – default information
/etc/login.defs – system-wide settings
/etc/skel – directory containing default files

Categories: Power Computing Tags: