unix shell commands

links: |- index -|- home -|
internal: | preamble | processes | comparisons | quick reference | file test | references | end |

see alphabetic list or
awk basename boot menu cat cd chmod chown cmake config convert copy count cp cpu-info cut cvs date debug df diff dirname dpkg dmsg dos2unix du echo editor expr fdupes file find firewall for free function gcc/g++ gdb git gksu glxinfo grep head heredoc hd hexdump hg http IFS ldconfig ldd ln(symlink) locate ls lshal lshw lsof lspci man menu Mercurial (hg) mkdir more mv nl nm  nocase os name pmap pwd ps read readelf repository rm rmdir script sed separator set sleep sort sound split su sudo svn symlink tail tar tee test tr top ufw ulimit uname uniq unzip updatedb w/who wc while xxd zip


This is just a personal set of commands used. It is not meant to be exhaustive, complete, or even accurate, so beware ;=)) And some things depend on EXACTLY which 'shell' you are running - see shell_categories.htm for more information on the various shells...

Also see an alphabetic list at http://en.wikipedia.org/wiki/List_of_Unix_programs ... with a brief description. And links to more details, where available, which may then have external links.


awk - text processing

'awk' is in fact a programming language!. A simple (or complex, depending on your point of view ;=))

~$ ls -l | awk 'NR!=1 {s+=$5} END {print "Total " s ", av. " s/(NR-1)}'

will skip the initial total block size output, and sum up the file sizes, listed in the 5th column by 'ls -l', and show the total, 's', and the average file size 's/(NR-1)', at the end.

Or using it to SUM the 2nd column of the $ pmap <pid> output -

~$ pmap <pid> | egrep "(anon|private|heap)" | \
   awk '{s+=$2} END {print "TOTAL " s " K" }'

The site http://www.vectorsite.net/tsawk_3.html has more examples.


Boot Menu

The boot menu is maintained in a file called /boot/grub/menu.lst. This can be manually change, or through the GUI menu editor. Whenever I use the 'menu' editor, I end up with a start-up message - "Undefined video mode number – Press Enter to see more or space to continue"!

This site - http://blog.edirectories.info/2008/04/how-to-fix-undefined-video-mode-number-in-ubuntu/ - give details of how to 'fix' this problem. As it says there :- Ubuntu users, open up a Terminal window and type:

$ gksudo gedit /boot/grub/menu.lst

Scroll down the file and you will find something that says  vga=791 or some other number.  Replace all instances of  vga=791 (or whatever it says) to vga=normal 

Make sure you change all of them or it may not work. Save the file and reboot. This should hopefully fix the problem! And of course, as it further says -
It’s a good idea to make a copy of the original "menu.lst" in case you do something wrong by accident.  Type:

sudo cp /boot/grub/menu.lst /boot/grub/menu.lst.old


config - configuration for various items

Some important configuration files...

There are lots in the /etc folder - some are -
/etc/fstab disk drives mounted at boot
/etc/hosts IP + hosts, plus IPv6 capable hosts list
/etc/resolv.conf dns information
/etc/shells list of valid login shells
/etc/apt/sources.lst apt-get source server
/etc/X11/xorg.conf Xorg configuration file
/etc/ssh/sshd_config configure default OpenSSH server app
Other locations -
/boot/grub/menu.lst list of boot options - see menu for more


for loop

Sample shell script for loop, to loop through all files in the current directory ...

for f in $FILES; do
  COUNT=`expr $COUNT + 1`
  LEN=`expr length $f`
  echo "$COUNT: Processing $f file ($LEN)..."
  # take action on each file... say...
  cat $f

In the above example, a 'space' is the 'separator'. This separator, called the IFS, or internal field separator, can be changed. This example -

for path in $PATH; do
  echo "full [$path], split into components"
  for p in $path; do
        if [ -z $p ]; then continue; fi
        CNT=`expr $CNT + 1`
        echo " $CNT: $p"

would show each of the elements in the PATH environment variable, and then show each element of the path. Note if $path starts with a '/' character, then you get a 'blank' $p, so this is tested and skipped in this case.

This is my script to install FlightGear scenery, after a massive 13GB ftp download, from the mirror site in Germany, ftp://ftp.de.flightgear.org/pub/fgfs/Scenery-1.0.1/, into the folder 'download'. You will note this copies the 'download' *.tgz file, unzips it, using gzip, to get a tar file, extracts all the files from the tar, using tar, deletes this tar file, and moves the original tgz into an 'installed' directory ...

echo "Installing scenery ..."
#cd into compile base directory
#get absolute path
for f in $FILES; do
        COUNT=`expr $COUNT + 1`
        LEN=`expr length $f`
        name=`echo "$f" | cut -c10-$LEN`
        SIZE=`ls -l $f | awk '{ print $5 }'`
        echo "$COUNT: File $f, size $SIZE"
        cp $f .
        gzip -d $name
        tar -xvf $TAR
        rm $TAR
        mv $f installed/$name
echo "Done $COUNT files ..."


functions - creating and calling a function

The basic syntax of a function is -

[ function ] name() { command-list }

If the optional 'function' is used, the the '()' are not required.

See http://www.gnu.org/software/bash/manual/bashref.html#Shell-Functions or
http://w3.pppl.gov/info/bash/Shell_Functions.html for example.


Process List

The command to view the process list is 'ps'. A simple

~$ ps

will show only the current user processes. Add -A to see ALL OF THEM!


Disk Partition Usage

To view all the mounted partitions, showing Size Used Avail Used%. A simple

~$ df -h
As at 20130414
Filesysttem Size Used Avail Use% Mounted on
/dev/sdb2    47G  36G  8.4G 81%  /
udev        989M 4.0K  989M  1%  /dev
tmpfs       401M 1.2M  400M  1%  /run
none        5.0M    0  5.0M  0% /run/lock
none       1001M 308K 1001M  1% /run/shm
/dev/sdb1   156G 108G   49G 70% /media/Disk2
/dev/sdb4    94G  78G   13G 87% /home

Used --help to see all the options!


convert line endings

While there is a command 'convert' as part of ImageMagick, to convert image files, here I ONLY refer to converting text file endings between DOS/Windows (CR/LF), to unix/linux (LF) line ending. A simple -

~$ dos2unix <file>

will do the trick, but you may need to do '$ sudo apt-get install tofrodos' first. $ dos2unix -h will show the options available. Have also read about a program called 'flip', '$ apt-get install flip', which seems to do the same job.


date [OPTIONS] [+FORMAT] - date/time output

The date command has many options $ date --help will show the big list.

~$ date +%N | sed -e 's/000$//' -e 's/^0//'

will show the nano-second portion of the time, with trailing and leading zeros stripped, if any, by sed!

Also try $ man date for more details.


find - Finding, searching and taking an action

As stated this command has MANY options. For example to find and delete 'temporary' or created files, you could run

~$ find . \( -name a.out -o -name '*.o' -o -name 'core' \) -exec rm {} \;

Note the 'escaped' brackets, '\(' and '\;'. The '-o' represents an OR. The final {} will take each find of the various names, and DELETE (rm) it! So take care!!!

This link - http://www.ibm.com/developerworks/aix/library/au-unix-find.html - has many more examples.

Or to find a set of files, and ask grep to search for some text in those files -

~$ find . -name '*.cxx' | xargs grep SGLoadTexture2D

This will pipe the set of files found to 'xargs' which will pass each file name to grep to search... neat...


heredoc - out a long string

To output a long string, retaining format, and spaces, use the 'heredoc' style - this starts with 'cat <<SOMENAME', and ends with a line beginning with the same 'SOMENAME', like -

~$ cat <<EOT [> out.txt]
line 1 with date `date +'%Y-%m-%d'`
  indented line 3 - $PROJ (would be expanded)
  this would retain the \n in the line.

As seen, this block of text can also be redirected to a file.


http - terminal textmode browsers

~$ lynx - is the classic text mode web browser.
~$ w3m  - has an interface with a difference.


sound - Ubuntu sound system

I found these commands on the FG development board, when some developers were discussing using 'festival ... or not' -

~$ lsmod | grep oss
~$ grep OSS /boot/config-$uname -r)

The first listed things like snd_pcm_oss, snd_seq_oss, snd_mixer_oss, etc, and the second listed about 7 items, like CONFIG_CHR_DEV_OSST=m, etc, which may or may not have anything to do with 'sound! While on John's system this produced CONFIG_SOUND_OSS_CORE=y, CONFIG_SND_OSSEMUL=y, CONFIG_SND_MIXER_OSS=m, etc. Obviously a lot more to explore here...


Where Is

There are many times I want to 'find' where something is located. The command 'find' will do this, but there are others, like 'whereis', and 'which'. A simple -

~$ whereis beep

If not found, then the result will be


or else it will display the path locations of 'beep' -

beep: /usr/bin/beep /usr/share/man/man1/beep.1.gz


~$ which beep

will show just


And of course, 'find' can also be used...


While loop

Here is an example to how to deal with a file, line by line using a 'while' loop -

git status > $TMP
while read line; do
    # process the $line
    echo "Length = ${#line}"
done < "$TMP"
echo "..."

or to inspect the 1st and 2nd words in a file line, using 'awk'...

git pull > $TMP
while read line; do
    # process the $line, and check for content
    x=`echo $line | awk '{print $1}'`
    y=`echo $line | awk '{print $2}'`
    if [ "$x" = "Already" ] && [ "$y" = "up-to-date." ]; then
     echo "Repo is UP-TO-DATE"
done < "$TMP"
echo "..."


Create a [symbolic] link - ln

To create a symbolic or hard link between files, or symbolic link for directories


For example, if there is a directory called 'temp1', then to create a link to that directory called 'temp2'

~$ ln -s temp1 temp2

will result in a listing, using 'ls -l' -

lrwxrwxrwx 1 name group         5 2009-02-01 13:05 temp2 -> temp1

If the folder temp1 contained the file 'temp1.txt' then the command -

~$ ls -L temp2

would show the file 'temp1.txt'. That is the -L dereferences the symbolic link, and shows the contents...


Directory Listing - ls

This command produces a directory list, somewhat like 'dir /w' in DOS. It has a myriad of options.

~$ ls -lABFgGtr

This will produce a listing:

-l = in long format - like "-rwxrwxrwx 1 name group 5 2009-02-01 13:05 file",
-A = of mostly-all except . and ..,
-B = excluding backups - files ending with a ~,
-F = classified, appending one of */=>@| to the entries,
-g = do not list owner,
-G = do not list group,
-t = sort by time,
-r = reverse order - oldest first.
--color = will add color to the output.
~$ ls --help

will show ALL the options in their full glory - short and long forms.


Shared Libraries - ldd and ldconf


You can see the list of the shared libraries used by a program using ldd. So, for example, you can see the shared libraries used by 'ls' by typing:

~$ ldd /bin/ls

Generally you'll see a list of the so-names being depended on, along with the directory that those names resolve to. In practically all cases you'll have at least two dependencies:

Beware: do not run ldd on a program you don't trust. As is clearly stated in the ldd(1) manual, ldd works by (in certain cases) by setting a special environment variable (for ELF objects, LD_TRACE_LOADED_OBJECTS) and then executing the program. It may be possible for an untrusted program to force the ldd user to run arbitrary code (instead of simply showing the ldd information). So, for safety's sake, don't use ldd on programs you don't trust to execute.

The 'ldd' tool uses the shared library loader, and can thus sometimes NOT find a required 'shared library'...

Also see nm for listing symbols in an object or executable binary.


Use just -? for help, or to see the LONG list of 'shared' libraries in the 'cache'

~$ ldconfig -p

The paths used to find shared libraries is controlled by the 'config' files in the /etc/ld.so.conf.d directory... like say libc.conf, which contains the lines -
# libc default configuration

If you wanted to add say /usr/local/lib64 to the 'loaders' cache, then create a file, say openscenegraph.conf, containing the line -
and run -

~$ ldconfig -v

to watch the update...

Note, to dump, view the contents of a 'shared library', if it is in ELF format, then see readelf ... or xxd for a hexified dump. Also see nm for listing symbols in an object or executable binary file.



Repositories are (online) source stores, where cooperative development can take place. Each developer can download (checkout/clone) the original source, make changes, and, if given the commit rights, can upload (commit) those changes back to the online version. The main line is usually called 'head', or 'trunk', but there can be many revisions, tags...

Known command line tools to 'manage' such repositories are :-

cvs Concurrent Version System http://www.cvshome.org/
svn Subversion http://subversion.tigris.org/
git Fast Version Control System http://git-scm.com/
hg Mercurial Distributed Source Control http://mercurial.selenic.com/

and no doubt others...


Table of Commands

Table of some commands, with a very brief explanation - there are usually MANY more options than the few examples shown. Most will give more information if followed by --help ...

Command syntax Purpose
date [OPTION] [+FORMAT] show the current date and time - more on date
diff [-ur] item1 item2 compare files, line by line. If used with -ur and the items are directories, then compare all files in one with all files in the other, and output in 'unified' format.
du [OPTION] [dir|file] show disk usage, of directory or file. Options, for a directory: -s for just the total; -h to show in good form, like 4.4G, etc; -b to show bytes, but will usually be less than disk usage; and -c for sub-directory totals. --help for more...
echo "some text" write 'some text' to the screen... more on echo and the heredoc style for larger outputs.
free show memory on the system
locate file Search the default /var/lib/mlocate/mlocate.db database for files matching the *file* given. When the OS is installed, and after major upgrades, run 'updatedb' to update the database.
ls list files - has many options, like -l for long listing - more on ls
lshal list Global Device List
lshw Hardware Lister. Run as $ sudo lshw
lsof -? Lists information about files opened by processes. This includes all file types - regular, directories, block or character, library, stream or network.
wc -{l|w|c} file count lines or words or characters in a file. For example, $ wc -l $FILE | cut -c1-2 to show number of lines in a file.
cp src dest copy source file(s) to destination. It can also duplicate a whole directory $ cp -ar[v] source/* destination. Note: -a = -dR --preserve=all (to copy all and keep date/times)
mv old-name new-name rename or move file
nl file Write each line from 'file', with line number added. Also see tail, to write lines at end of the file.
nm file List symbols in an (object or executable) file. Also see ldd for listing shared libraries used by a binary.
rm file delete a file. $ rm -f file to force deletion. -r to recursively delete a directory
grep pattern file search for strings in a file - like $ grep 'searchstring' file.txt - more on grep
glxinfo Output direct rendering: Yes (or No), and lots of glx and OpenGL info and extensions, list of supported modes. Like $ glxinfo | grep direct - a little more
cut -b<column> file cut data by column width, like get character positions 5 to 9 - $ cut -b5-9 file.txt
cat file.txt write file.txt to stdout (your screen) - like 'type file.txt' in windows
cd [<dir>|~|-] Change directory - If say $ cd /etc is given, and the directory exists, will change to that directory. Both $ cd and $ cd ~ will change to the $HOME directory. And $ cd - will change to the previous directory. A suggested alias, that will print the current directory after the change would be
alias cd `cd \!*;pwd`
cat /proc/cpuinfo show current CPU information
chmod [opt] file Change the permission options, like a+x to make executable
chown [opt] o:g file Change the owner:group of a file
cmake <dir> CMake is a cross-platform, open-source build system - http://www.cmake.org/ - more on cmake
cvs Concurrent Version System - checkout, update, and diff a repository
dpkg -l display a list of installed packages. --help for many more options.
fdupes [-rS] <dir> Scan directory for duplicate files. 'r' = recursive, 'S' = reports sizes
file some-file describe what type of file some-file is
git clone URI download (clone) a git repository. more on git
read var prompt the user for input and write it into a variable (var)
sort file.txt sort lines in file.txt
uniq remove duplicate lines, used in combination with sort since uniq removes only duplicated consecutive lines. example: $ sort file.txt | uniq


ufw [command] uncomplicated firewall (for Ubuntu 8.04 LTS+) - see https://wiki.ubuntu.com/UbuntuFirewall
ulimit Establish various user limits. $ ulimit -a will show the current list.
uname return certain system information. $ uname -r will return the kernel version, like 2.6.24-26-generic; -m the machine hardware, like x86_64; etc. Use -a for an 'all' (known) output.
expr do math in the shell. example: add 2 and 3 expr 2 "+" 3 or in a script VALUE=`expr 2 + 3` more...
find search for files - example: search by name: $ find . -name *file* [-print|-ls] will find all files with 'file' in their name. -print is the default, so not required. This command has many options. more on find.
tee write data to stdout (your screen) and to a file. Normally used like this: $ cmd | tee out-file - It writes the output of cmd to the screen AND to the file 'out-file'.
tr Translate, squeeze, and/or delete characters.
LSB_REL=`lsb_release -a 2>/dev/null | tr "\n\t" " "`
would replace all new line, and tab characters with a space.
$ echo this | tr "[:lower:]" "[:upper:]" would output THIS. That is a case translation, nocase...
A nifty splitting of $PATH - echo $PATH | tr ':' '\n'
See also 'sed' and 'awk', which can do similar things, and $ dd if=in_file of=new_file -ucase would copy 'in_file' to 'new_file', all in upper case.
basename file return just the file name of a given name and strip the directory path - Example: $ basename /bin/tux returns just tux, or in a script BN=`basename $0`
dirname file return just the directory name of a given name and strip the actual file name - example: $ dirname /bin/tux returns just /bin
w/who show list of users...
head file print some lines from the beginning of a file


hg [-v help] Mercurial Distributed Source Control Management (DSCM) - commands: clone: make repository copy; diff: diff repo; fetch: pull changes, and merge; etc - it is a 'Distributed Version Control System' (DVCS).
ps show processes. To show all processes $ ps -A will list PID TTY TIME CMD. To change the output $ ps -A -o user,pid,ucmd,args will list USER PID CMD COMMAND, $ ps L to list the output choices. more on 'ps'
top show a dynamic process list
pmap <pid> report memory map of a process. Say $ pmap <pid> | grep anon to show allocations, etc...
man some_command open the manual for the command, if it exists, in the 'vi' editor. Use ':q' to quit.
more text_file to output the contents of a text file, one screen at a time
mkdir name to create a directory. If a complex path, and the parent directories also need be create, then use -p
rmdir name remove an empty directory of 'name'
pwd show the current directory
set In shell script 'set -e' will cause the script to abort if an operation returns 'errexit' 1. 'set +e' will turn off that action. more on 'set'
sleep NUMBER pause for NUMBER seconds
su log in as super user (root). Usually, in some systems, and depending on the shell 'init' file(s), like ~/.bashrc..., the prompt will change form '$', to '#'.
See sudo to do this on a 'temporary' basis...
sudo (and gksu) provide limited super user priviledges to specific users. maybe mean 'super-user-do'. gksu can be used on GUI apps, like $ gksu gedit <filename>
svn Subversion command line client - Source Control System. Commands: checkout (co): create new repository; update (up): update a repository; diff (di): diff a repository
tail [-n=N] file print some lines from the end of a file. Use -n=N to show more, less than default last 10.
sed sed is basically a find and replace program. It reads text from standard input (e.g from a pipe) and writes the result to stdout (normally the screen). The search pattern is a regular expression (see references). This search pattern should not be confused with shell wildcard syntax. To replace the string linuxfocus with LinuxFocus in a text file use:
$ cat text.file | sed 's/linuxfocus/LinuxFocus/' > newtext.file
This replaces the first occurrence of the string linuxfocus in each line with LinuxFocus. If there are lines where linuxfocus appears several times and you want to replace all use:
$ cat text.file | sed 's/linuxfocus/LinuxFocus/g' > newtext.file


tar archive a set of file
create: $ tar -caf test.tgz * achive to test.tgz, and compress
view: $ tar -tvzf test.tgz view the contents of an archive
extract: $ tar -xvzf test.tgz expand and write files
zip create: archive a set of file into zip file. List see 'unzip'.
unzip view: -l[v] to list the contents of a zip file.
extract: to extract file, with directories.
Options: -j - junk directories
-n - never overwrite existing
-x xlist - exclude files in xlist
-h - display help message
updatedb Run at installation, or after major upgrades to update files in the mlocate database, default /var/lib/mlocate/mlocate.db. See locate for searching this database.
awk Most of the time awk is used to extract fields from a text line. The default field separator is space. To specify a different one use the option -F.
$ cat file.txt | awk -F, '{print $1 "," $3 }'
Here we use the comma (,) as field separator and print the first and third ($1 $3) columns. If file.txt has lines like:
Adam Bor, 34, India
          Kerry Miller, 22, USA
then this will produce:
Adam Bor, India
          Kerry Miller, USA
There is much more you can do with awk. more on awk
gcc / g++ The compiler, but also runs linker and librarian. Has a neat output with -print-search-dirs to see of list of where it searches for components
gdb a debug tool. The general runtime is $ gdb [options] --args executable [argument]. After it load, (gdb) help will list the help options, and (gbd) run will run the executable. On say a segfault, 'bt' is helpful, and 'quit' will fully exit. more on gdb
readelf -a file.so output contents of an ELF formatted executable, library or object file
hd file
hexdump file
xxd -g 1 file
To produce a hexified dump of the file contents. hexdump and xxd normally show as 16-bits. Use xxd -g 1 for byte display. -h or --help for options. see readelf to dump an ELF binary file.


Some Windows and Linux Command Comparisons

This section adapted from -
which was from http://www.yolinux.com/TUTORIALS/unix_for_dos_users.html ...
an adaptation of an adaptation ;=)) not intended as a complete list!

Windows Command Linux Shell Command Action
dir ls -l [-lF] List directory contents - add -a for all files. -1f for one per line. Use $ df -k to show space remaining on file system.
dir *.* /o-d
dir *.* /v /os
dir /s
dir /aa
ls -tr
ls -ls
ls -R
ls -a
List by reverse time of modification/creation.
List files and size
List directory/sub-directory contents recursively.
List hidden files.
tree ls -R List directory recursively
cd (or chdir) cd (pwd) Change (or show) directory
md (or mkdir) mkdir Make a new directory
rd (or rmdir) rmdir Remove a directory, if it is empty
del (or erase) rm -iv Remove a file
rmdir /S (NT)
deltree (W95?)
rm -R Remove all directories and files below given directory
copy cp -piv Copy a file
xcopy cp -R Copy all file of directory recursively
rename or move mv -iv Rename/move a file
type cat Dump contents of a file to users screen
more more Pipe output a single page at a time
help or command /? man Online manuals
grep Look for a word in files given in command line
comp diff Compare two files and show differences. Also see comm and cmp.
fc diff Compare two files and show differences. Also see comm and cmp.
echo text echo text Echo text to screen
date or time date Show date, set date with permissions
sort sort Sort data alphabetically/numerically
edit file.txt emacs Edit a file. There are many editors in unix - gedit, kate, pico, vi, vim, to name a few... but emacs is 'historic' ;=))
print lpr Print a file (at present my 'Dell AIO 810' is NOT supported by Unbuntu ;=(()
mem free (or top) Show free memory on system (per process)
tasklist ps -aux
List executable name, process ID number and memory usage of active processes
chdisk du -s Disk usage.
pkzip tar and zip Compress and uncompress files/directories. Use tar to create compilation of a directory before compressing. Linux also has compress, gzip


Quick Reference

This is a quick reference guide to the meaning of some of the less easily guessed commands and codes. These are use in a 'test', like 'if test -z "$CMD"; then', or 'if [ -z "$CMD" ]; then ... statement ... [else ... statements ... ] fi'

Command Description and Example
& Run the previous command in the background ls &
&& Logical AND if [ "$foo" -ge "0" ] && [ "$foo" -le "9" ]; then
|| Logical OR if [ "$foo" -lt "0" ] || [ "$foo" -gt "9" ]; then (not in Bourne shell)
^ Start of line grep "^foo"
$ End of line grep "foo$"
= String equality (cf. -eq) if [ "$foo" = "bar" ]; then
! Logical NOT if [ "$foo" != "bar" ]; then
$$ PID of current shell echo "my PID = $$"
$! PID of last background command ls & echo "PID of ls = $!"
$? exit status of last command ls ; echo "ls returned code $?"
$0 Name of current command (as called) echo "I am $0"
$1 Name of current command's first parameter echo "My first argument is $1"
$9 Name of current command's ninth parameter echo "My ninth argument is $9"
$# Commands parameter count echo "Got $# parameters"
$@ All of current command's parameters (preserving whitespace and quoting) echo "My arguments are $@"
$* All of current command's parameters (not preserving whitespace and quoting) echo "My arguments are $*"
-eq Numeric Equality if [ "$foo" -eq "9" ]; then
-ne Numeric Inquality if [ "$foo" -ne "9" ]; then
-lt Less Than if [ "$foo" -lt "9" ]; then
-le Less Than or Equal if [ "$foo" -le "9" ]; then
-gt Greater Than if [ "$foo" -gt "9" ]; then
-ge Greater Than or Equal if [ "$foo" -ge "9" ]; then
-z String is zero length if [ -z "$foo" ]; then
-n String is not zero length if [ -n "$foo" ]; then
( ... ) Parenthesis = Function definition = function myfunc() { echo hello }
File test operators
-e file exists if [ -e $file ]; then
-a file exists. This is identical in effect to -e. It has been "deprecated," and its use is discouraged. if [ -a $file ]; then
-f file is a regular file (not a directory or device file) if [ -f $file ]; then
-s file is not zero size if [ -s $file ]; then
-d file is a directory if [ -d $dir ]; then
-b file is a block device (floppy, cdrom, etc.) if [ -b $file ]; then
-c file is a character device (keyboard, modem, sound card, etc.) if [ -c $file ]; then
-p file is a pipe if [ -p $file ]; then
-h file is a symbolic link if [ -h $file ]; then
-L file is a symbolic link if [ -L $file ]; then
-S file is a socket if [ -S $file ]; then
-t file (descriptor) is associated with a terminal device. This test option may be used to check whether the stdin ([ -t 0 ]) or stdout ([ -t 1 ]) in a given script is a terminal. if [ -t $file ]; then
-r read permission (for the user running the test) if [ -r $file ]; then
-w write permission (for the user running the test) if [ -w $file ]; then
-x execute permission (for the user running the test) if [ -x $file ]; then
-g set-group-id (sgid) flag set on file or directory. If a directory has the sgid flag set, then a file created within that directory belongs to the group that owns the directory, not necessarily to the group of the user who created the file. This may be useful for a directory shared by a workgroup. if [ -g $file ]; then
-u set-user-id (suid) flag set on file. A binary owned by root with set-user-id flag set runs with root privileges, even when an ordinary user invokes it. This is useful for executables (such as pppd and cdrecord) that need to access system hardware. Lacking the suid flag, these binaries could not be invoked by a non-root user.
-rwsr-xr-t 1 root  178236 Oct  2  20:00 /usr/sbin/pppd   
A file with the suid flag set shows an s in its permissions. if [ -u $file ]; then
-k sticky bit set. Commonly known as the "sticky bit," the save-text-mode flag is a special type of file permission. If a file has this flag set, that file will be kept in cache memory, for quicker access. If set on a directory, it restricts write permission. Setting the sticky bit adds a t to the permissions on the file or directory listing.
drwxrwxrwt 7 root     1024 May 19 21:26 tmp/    
If a user does not own a directory that has the sticky bit set, but has write permission in that directory, he can only delete files in it that he owns. This keeps users from inadvertently overwriting or deleting each other's files in a publicly accessible directory, such as /tmp. (The owner of the directory or root can, of course, delete or rename files there.) if [ -k $file ]; then
-O you are owner of file if [ -O $file ]; then
-G group-id of file same as yours if [ -G $file ]; then
-N file modified since it was last read if [ -N $file ]; then
f1 -nt f2 file f1 is newer than f2 if [ $f1 -nt $f2 ]; then
f1 -ot f2 file f1 is older than f2 if [ $f1 -ot $f2 ]; then
f1 -ef f2 files f1 and f2 are hard links to the same file! if [ $f1 -ef $f2 ]; then
"not" -- reverses the sense of the tests above (returns true if condition absent).



Date Link
2010-01-03 mercury.chem.pitt.edu/~sasha/.../article216.shtml
2010-01-03 http://www.unix.com/unix/linux/f-2-p-3.html


Alphabetic List

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z top

A: awk
B: basename boot menu
C: cat cd chmod chown cmake config convert count cp cut cpu-info cvs
D: date debug df  diff dirname dmsg dos2unix dpkg du
E: echo expr
F: fdupes file find firewall for free function
G: gcc/g++ gdb(debug) git gksu glxinfo grep
H: head hd hexdump hg http
L: ldconfig ldd ln(symlink) locate ls lshal lshw lsof lspci
M: man menu Mercurial (hg) mkdir more mv
N: nl nm nocase
O: os_name
P: pmap ps pwd
R: read readelf repository rm rmdir
S: script sed separator set sleep sort sound su sudo svn symlink
T: tail tar tee test top tr
U: ufw ulimit uname uniq unzip updatedb
W: w/who wc whereis/which while
X: xxd
Z: zip


checked by tidy Valid HTML 4.01 Transitional