How to genrate Random Password from Commandline

One of the great things about Linux is that you can do the same thing hundreds of different ways—even something as simple as generating a random password can be accomplished with dozens of different commands. Here’s 10 ways you can do it.

We gathered all of these commands from Command-Line Fu and tested them out on our own Linux PC to make sure they work. You should be able to use at least some of these on Windows with Cygwin installed, though we didn’t test all of them—the last one definitely works though.
Generate a Random Password

For any of these random password commands, you can either modify them to output a different password length, or you can just use the first x characters of the generated password if you don’t want such a long password. Hopefully you’re using a password manager like LastPass anyway so you don’t need to memorize them.

This method uses SHA to hash the date, runs through base64, and then outputs the top 32 characters.

date +%s | sha256sum | base64 | head -c 32 ; echo

This method used the built-in /dev/urandom feature, and filters out only characters that you would normally use in a password. Then it outputs the top 32.

< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c${1:-32};echo;

This one uses openssl’s rand function, which may not be installed on your system. Good thing there’s lots of other examples, right?

openssl rand -base64 32

This one works a lot like the other urandom one, but just does the work in reverse. Bash is very powerful!

tr -cd '[:alnum:]' < /dev/urandom | fold -w30 | head -n1

Here’s another example that filters using the strings command, which outputs printable strings from a file, which in this case is the urandom feature.

strings /dev/urandom | grep -o '[[:alnum:]]' | head -n 30 | tr -d '\n'; echo

Here’s an even simpler version of the urandom one.

< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c6

This one manages to use the very useful dd command.

dd if=/dev/urandom bs=1 count=32 2>/dev/null | base64 -w 0 | rev | cut -b 2- | rev

You can even create a random left-hand password, which would let you type your password with one hand.

howtogeek.com

Share

How to disable ProFTP in Linux

First, look in your /etc/xinetd.d/ directory and see if there’s a file named psa_ftp in there. If not, you might have to make this change in your /etc/xinetd.conf file.

Open up the file as root, and look for the following section:

service ftp
{
disable = yes
socket_type = stream
protocol = tcp
wait = no
user = root
instances = UNLIMITED
server = /usr/sbin/in.proftpd
server_args = -c /etc/proftpd.conf
}

Change the disable = no line to disable = yes as shown above.

Run the following command to restart xinetd

/etc/init.d/xinetd restart This Article is taken from

Share

How to Install Nginx with PHP5 and MySQL on CentOS 5.5

Nginx (pronounced “engine x”) is a free, open-source, high-performance HTTP server. Nginx is known for its stability, rich feature set, simple configuration, and low resource consumption. This tutorial shows how you can install Nginx on a CentOS 5.5 server with PHP5 support (through FastCGI) and MySQL support.

I do not issue any guarantee that this will work for you!

1 Preliminary Note

In this tutorial I use the hostname server1.example.com with the IP address 192.168.0.100. These settings might differ for you, so you have to replace them where appropriate.

2 Installing MySQL 5

First we install MySQL 5 like this:

yum install mysql mysql-server

Then we create the system startup links for MySQL (so that MySQL starts automatically whenever the system boots) and start the MySQL server:

chkconfig –levels 235 mysqld on
/etc/init.d/mysqld start

Now check that networking is enabled. Run

netstat -tap | grep mysql

It should show something like this:

[root@server1 ~]# netstat -tap | grep mysql
tcp 0 0 *:mysql *:* LISTEN 2388/mysqld
[root@server1 ~]#

If it does not, edit /etc/my.cnf and comment out the option skip-networking:

vi /etc/my.cnf

[...]
#skip-networking
[...]

and restart your MySQL server:

/etc/init.d/mysqld restart

Run

mysql_secure_installation

to set a password for the user root (otherwise anybody can access your MySQL database!):

[root@server1 ~]# mysql_secure_installation

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL
SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!

In order to log into MySQL to secure it, we’ll need the current
password for the root user. If you’ve just installed MySQL, and
you haven’t set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none): < -- ENTER
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MySQL
root user without the proper authorisation.

Set root password? [Y/n] <-- ENTER
New password: <-- yourrootsqlpassword
Re-enter new password: <-- yourrootsqlpassword
Password updated successfully!
Reloading privilege tables..
... Success!

By default, a MySQL installation has an anonymous user, allowing anyone
to log into MySQL without having to have a user account created for
them. This is intended only for testing, and to make the installation
go a bit smoother. You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] <-- ENTER
... Success!

Normally, root should only be allowed to connect from 'localhost'. This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] <-- ENTER
... Success!

By default, MySQL comes with a database named 'test' that anyone can
access. This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] <-- ENTER
- Dropping test database...
... Success!
- Removing privileges on test database...
... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] <-- ENTER
... Success!

Cleaning up...

All done! If you've completed all of the above steps, your MySQL
installation should now be secure.

Thanks for using MySQL!This Article is taken fromhowtoforge.com

Share

How to Upload Files to an FTP site via a Batch Script

This script can be used from the command line as a ‘no questions asked’ method of uploading one or many files with a single command. Additionally, you can call this script from batch files to perform automated file uploads. A few uses for this include (but, of course, not limited to):

* Include in backup scripts to send data offsite.
* Upload html/php/etc. files to a web server with a single command.
* Create shortcuts to send a common group of files (such as a web site’s source pages).

Configuration

The only configuration required is to set the FTP server connection information. Under the “Connection information” line, set the following:

* Server – The FTP Server you are uploading to. You can either enter the DNS name (ftp.myserver.com) or IP address (1.2.3.4).
* UserName – Your user name for connecting to FTP server.
* Password – Your password for connecting to the FTP server.

Depending on your firewall settings, the first time you run this script you may be prompted to allow FTP to connect to the Internet. Setting this to never prompt you again should remove future warnings.
The Script

@ECHO OFF
ECHO Upload to FTP
ECHO Written by: Jason Faulkner
ECHO SysadminGeek.com
ECHO.
ECHO.

REM Usage:
REM UploadToFTP [/L] FileToUpload
REM
REM Required Parameters:
REM FileToUpload
REM The file or file containing the list of files to be uploaded.
REM
REM Optional Parameters:
REM /L When supplied, the FileToUpload is read as a list of files to be uploaded.
REM A list of files should be a plain text file which has a single file on each line.
REM Files listed in this file must specify the full path and be quoted where appropriate.

SETLOCAL EnableExtensions

REM Connection information:
SET Server=
SET UserName=
SET Password=

REM —- Do not modify anything below this line —-

SET Commands=”%TEMP%\SendToFTP_commands.txt”

REM FTP user name and password. No spaces after either.
ECHO %UserName%> %Commands%
ECHO %Password%>> %Commands%

REM FTP transfer settings.
ECHO binary >> %Commands%

IF /I {%1}=={/L} (
REM Add file(s) to the list to be FTP’ed.
FOR /F “usebackq tokens=*” %%I IN (“%~dpnx2″) DO ECHO put %%I >> %Commands%
) ELSE (
ECHO put “%~dpnx1″ >> %Commands%
)

REM Close the FTP connection.
ECHO close >> %Commands%
ECHO bye >> %Commands%

REM Perform the FTP.
FTP -d -i -s:%Commands% %Server%

ECHO.
ECHO.

REM Clean up.
IF EXIST %Commands% DEL %Commands%

ENDLOCAL

LinksThis Article is taken from

Share

Summer End Sale of uCertify

uCertify is offering an amazing discount of upto 45%.! Check out the offer!

Any 4+ PrepKits for $64.99 each (TRIPLE WOW! That’s a 45% savings off the list price!)

Any 3 PrepKits for $69.99 each (DOUBLE WOW! That’s a 40% savings off the list price!)

Any 2 PrepKits for $72.99 each (WOW! That’s a 38% savings off the list price!)

HURRY! Feel the warmth of these great savings on any test preparation software from uCertify. This is the golden opportunity from uCertify. Time is running out so don’t wait, just go and buy your guide to the certification path.

You can also take the advantage of their additional 5% discount by joining their Facebook page! All you have to do is like their page to be entitled to this private discount.
http://www.facebook.com/Certifications?v=app_4949752878

Share

uCertify’s Back 2 School Sale : Save 40%

Guys,uCertify is offering a 40% discount on all Prepkits. A user can select from extensive selection of over 300 PrepKits to help prepare for their IT certification exam(s). For a limited time only, uCertify is offering a humongous 40% discount! Buy any two PrepKits for $139.99 (compare to about $119.99 for each PrepKit!).

This time you can also take advantage of an additional discount by joining us on Facebook! All anyone have to do is like our page to be entitled to this private discount.

http://www.facebook.com/pages/ucertify/176752623633?v=app_4949752878

Share

SSH Tips for the day

‘When you are forwarding ports through a tunnel, either locally or remotely (i.e., with the -L or -R switches), you can modify the session real-time. The way that you do this is after you start the session, you press SHIFT + ` + c (The ` key also has a ~ in it, which is the actual keypress sent to the session). If it doesn’t work the first time, press ENTER a couple of times and try it again. Once you get the “ssh>” prompt, type “?” for the commands you can put in. Here’s an example session:

[0908][scott@dev:~]$ ssh -R 8080:suseblog.com:8080 scott@suseblog.com
Password:
Last login: Thu Oct 15 11:59:43 2009 from 67.214.232.162
Have a lot of fun…
[1109][scott@mail:~]$ [PRESS SHIFT + ` + c HERE]
ssh> ?
Commands:
-L[bind_address:]port:host:hostport Request local forward
-R[bind_address:]port:host:hostport Request remote forward
-KR[bind_address:]port Cancel remote forward
[PRESS ENTER HERE]
[1110][scott@mail:~]$ [PRESS SHIFT + ` + c HERE]
ssh> -R8080:letslearnlinux.com:1080
Forwarding port.

[1110][scott@mail:~]$’

Share

Cropping Multiple Images in the Same Way

‘Getting the right cropping values using GIMP

In 5 steps:
Where to find the cropping values
1. Open up GIMP.
2. Open one of the images in GIMP.
3. Using the Rectangle Select Tool (hotkey “R”), select the area you want to be cropped.
4. Note the X, Y, Width and Height values GIMP gives you (have a look at the picture, you can find them in the GIMP main window).
5. Close GIMP (or leave it open if you plan to use it again soon).

We now have the values we need to tell the mogrify utility what to crop. Let’s go on and write a line that’ll execute mogrify in such a way that it’ll crop all our images!
Cropping the images

Now we’ll start working in the terminal. Open up your favourite one and cd to the directory where the images are located. Note that I strongly recommend having only the images that are to be cropped in the directory, nothing more. It saves you a lot of trouble. Well then, let’s start with the mogrify command. The syntax for cropping is as follows:

[rechosen@localhost ~]$ mogrify -crop {Width}x{Height}+{X}+{Y} image.png

Now don’t be scared, the {Width}, {Height} and so on simply are the places where you should put the values you got from GIMP! Note that I use a png file as an example, while mogrify is able to handle over 100 image file types. You don’t have to use png files with it. Anyway, if I’d fill in the values from the screenshot, the mogrify command would look like this:

[rechosen@localhost ~]$ mogrify -crop 643×393+7+83 image.png

The logic behind this system is the following: crop an area of 643 by 393 pixels, starting at 7 pixels from the left and 83 pixels from the top of the image. Got it? Ok then. The above command would overwrite image.png with a cropped version. But this still manipulates just a single image. The easiest way to make mogrify modify all images is just this:

[rechosen@localhost ~]$ mogrify -crop 643×393+7+83 *.png

The asterisk makes bash fill in all png files in the current directory, and mogrify will handle them all happily. After a (hopefully short) wait, all the images will have been cropped. If you want to crop images of an other format, just change “*.png” to, for example, “*.jpg” or “*.gif”.

You might want to give the cropped images other names, so that the original images will not be overwritten and it will be clear which images have been cropped and which haven’t. This is more complex, but hey, we’re working on Linux! Everything is possible if you take the time to write it.
Renaming the cropped images

In order to give the cropped images other names, we’ll use a bash loop. This time, we’ll use the convert utility. It is from the same family as mogrify, but it makes it easier for us to output to an other filename. I won’t explain the whole loop, as most of it is bash knowledge, but I will tell you which things you can/should alter to get the right results. There are loops for two cases, just pick the one of which you like the file naming the most.

* Case 1: You want the output files to be named like this: originalfile.png => cropped_originalfile.png (again, you can insert any of the over 100 supported image formats here, I just like png). The loop should be like this:

[rechosen@localhost ~]$ for file in *.png; do convert -crop {Width}x{Height}+{X}+{Y} $file cropped_$file; done

You should replace “png” with the extension you want (think of jpg, gif, png (of course) and so on), and the “{Width}”, “{Height}” etc with the values you got from GIMP. You may also replace “cropped_” with any prefix you like.
* Case 2: You want the output files to be named like this: originalfile.png => originalfile_cropped.png (or originalfile.jpg => originalfile_cropped.jpg, you name it). In that case, you should use the following loop:

[rechosen@localhost ~]$ for file in *.png; do convert -crop {Width}x{Height}+{X}+{Y} $file ${file%.png}_cropped.png; done

Again, replace “png” with the extension you want (watch it, there are 3 instances of it) and the “{Width}”, “{Height}” etc with the values you got from GIMP. You can also replace “_cropped” with any suffix you like.

Note that you can, in this case, easily modify the output format: if you want to output the cropped images in jpg format, you can just replace the third instance of “png” with “jpg”, no matter what format your input files are. The convert utility will detect it and change the image format automatically. ‘

Share

Creating an mpeg with mencoder that plays on Windows Media Player

‘Let’s have a look at a rather simple mencoder command that should create a WMP-compatible MPEG file:

[rechosen@localhost ~]$ mencoder
-oac lavc -ovc lavc -lavcopts acodec=mp2:vcodec=mpeg2video:mbd=1:vbitrate=1800 -of mpeg -o

Replace “
” with the video source (for example a file or a DVD scene) and “” with the file you want the output to be written to (e.g. “samplemovie.mpg” or “dvdbackup.mpeg”). You can also replace the value after “vbitrate=” with a higher or lower bitrate, depending on the desired quality of the outputfile (you could also leave it away entirely, but it will then default to 800, which is quite low and therefore pretty much only suitable for very low resolution movies).

Note that the above example will try to encode the movie at the same resolution and fps as the source. However, this does not always work correctly and also isn’t always what you want. Furthermore, the above example doesn’t use two-pass encoding. Two-pass encoding is useful because it results in a higher quality outputfile with about the same size (it needs to read the source twice, though).
A more feature-rich example

The next example features rescaling (adapting the resolution), specifies a framerate for the outputfile and encodes in two passes.

[rechosen@localhost ~]$ for i in {1,2}; do mencoder
-oac lavc -ovc lavc -lavcopts acodec=mp2:vcodec=mpeg2video:mbd=1:vpass=$i:vbitrate=1800 -of mpeg -ofps 25 -vf scale=640:480 -o ; done

Replace “
” with any source that can be read twice (a file or a DVD scene) and “” with the file you want the encoded data to be written to. You can alter the values after “-ofps=” and “-vf scale=” to change the framerate and the resolution of the outputfile, respectively (and of course you can alter the vbitrate again, too).

One more handy trick: you can set only the width of the encoded video and let mencoder determine the height, keeping the right aspect ratio:

[rechosen@localhost ~]$ for i in {1,2}; do mencoder
-oac lavc -ovc lavc -lavcopts acodec=mp2:vcodec=mpeg2video:mbd=1:vpass=$i:vbitrate=1800 -of mpeg -ofps 25 -vf scale -zoom -xy 640 -o ; done

Again, replace “
” with any source that can be read twice (a file or a DVD scene) and “” with the file you want the encoded data to be written to. You can alter the value after “-ofps=” again to change the framerate of the outputted data, and after “-zoom -xy ” is the value to change if you want a different width (note that values less than or equal to 8 will be interpreted as scaling factors, not as the width of the outputted video).’

Share

If Condition in Bash Script

‘If you use bash for scripting you will undoubtedly have to use conditions a lot, for example for an if … then construct or a while loop. The syntax of these conditions can seem a bit daunting to learn and use. This tutorial aims to help the reader understanding conditions in bash, and provides a comprehensive list of the possibilities. A small amount of general shell knowledge is assumed.

Difficulty: Basic – Medium
Introduction

Bash features a lot of built-in checks and comparisons, coming in quite handy in many situations. You’ve probably seen if statements like the following before:

if [ $foo -ge 3 ]; then

The condition in this example is essentially a command. It may sound strange, but surrounding a comparison with square brackets is the same as using the built-in test command, like this:

if test $foo -ge 3; then

If $foo is Greater then or Equal to 3, the block after ‘then’ will be executed. If you always wondered why bash tends to use -ge or -eq instead of >= or ==, it’s because this condition type originates from a command, where -ge and -eq are options.
And that’s what if does essentially, checking the exit status of a command. I’ll explain that in more detail further in the tutorial.
There also are built-in checks that are more specific to shells. What
about this one?

if [ -f regularfile ]; then

The above condition is true if the file ‘regularfile’ exists and
is a regular file. A regular file means that it’s not a block or
character device, or a directory. This way, you can make sure a usable
file exists before doing something with it. You can even check if a
file is readable!

if [ -r readablefile]; then

The above condition is true if the file ‘readablefile’ exists and is readable. Easy, isn’t it?
The syntax of an if statement (a short explanation)

The basic syntax of an if … then statement is like this:

if ; then

fi

The condition is, depending on its type, surrounded by certain
brackets, eg. [ ]. You can read about the different types further on
in the tutorial. You can add commands to be executed when the condition is false using the else keyword, and use the elif (elseif) keyword to execute commands on another condition if the primary condition is false. The else keyword always comes last. Example:

if [ -r somefile ]; then
content=$(cat somefile)
elif [ -f somefile ]; then
echo “The file ‘somefile’ exists but is not readable to the script.”
else
echo “The file ‘somefile’ does not exist.”
fi

A short explanation of the example: first we check if the file somefile is readable (“if [ -r somefile ]“). If so, we read it into a variable. If not, we check if it actually exists (“elif [ -f somefile ]“). If that’s true, we report that it exists but isn’t readable (if it was, we would have read the content). If the file doesn’t exist, we report so, too. The condition at elif is only executed if the condition at if was false. The commands belonging to else are only executed if both conditions are false.
The basic rules of conditions

When you start writing and using your own conditions, there are some rules you should know to prevent getting errors that are hard to trace. Here follow three important ones:

1. Always keep spaces between the brackets and the actual check/comparison. The following won’t work:

if [$foo -ge 3]; then

Bash will complain about a “missing `]’”.
2. Always terminate the line before putting a new keyword like “then”. The words if, then, else, elif and fi are shell keywords, meaning that they cannot share the same line. Put a “;” between the previous statement and the keyword or place the keyword on the start of a new line. Bash will throw errors like “syntax error near unexpected token `fi’” if you don’t.
3. It is a good habit to quote string variables if you use them in conditions, because otherwise they are likely to give trouble if they contain
spaces and/or newlines. By quoting I mean:

if [ "$stringvar" == "tux" ]; then

There are a few cases in which you should not
quote, but they are rare. You will see one of them further on in the tutorial.

Also, there are two things that may be useful to know:

1. You can invert a condition by putting an “!” in front of it. Example:

if [ ! -f regularfile ]; then

Be sure to place the “!” inside the brackets!
2. You can combine conditions by using certain operators. For the single-bracket syntax that we’ve been using so far, you can use “-a” for and and “-o” for or. Example:

if [ $foo -ge 3 -a $foo -lt 10 ]; then

The above condition will return true if $foo contains an integer greater than or equal to 3 and Less Than 10. You can read more about these combining expressions at the respective condition syntaxes.

And, one more basic thing: don’t forget that conditions can also be used in other statements, like while and until. It is outside the scope of this tutorial to explain those, but you can read about them at the Bash Guide for Beginners.

Anyway, I’ve only shown you conditions between single brackets so far. There are more syntaxes, however, as you will read in the next section.
Different condition syntaxes

Bash features different syntaxes for conditions. I will list the three of them:
1. Single-bracket syntax

This is the condition syntax you have already seen in the previous paragraphs; it’s the oldest supported syntax. It supports three types of conditions:

* File-based conditions
o Allows different kinds of checks on a file. Example:

if [ -L symboliclink ]; then

The above condition is true if the file ‘symboliclink’ exists and is a symbolic link. For more file-based conditions see the table below.
* String-based conditions
o Allows checks on a string and comparing of strings. Example one:

if [ -z "$emptystring" ]; then

The above condition is true if $emptystring is an empty string or an uninitialized variable. Example two:

if [ "$stringvar1" == "cheese" ]; then

The above condition is true if $stringvar1 contains just the string “cheese”. For more string-based conditions see the table below.
* Arithmetic (number-based) conditions
o Allows comparing integer numbers. Example:

if [ $num -lt 1 ]; then

The above condition returns true if $num is less than 1. For more arithmetic conditions see the table below.

2. Double-bracket syntax

You may have encountered conditions enclosed in double square brackets already, which look like this:

if [[ "$stringvar" == *string* ]]; then

The double-bracket syntax serves as an enhanced version of the single-bracket syntax; it mainly has the same features, but also some important differences with it. I will list them here:

* The first difference can be seen in the above example; when comparing strings, the double-bracket syntax features shell globbing. This means that an asterisk (“*”) will expand to literally anything, just as you probably know from normal command-line usage. Therefore, if $stringvar contains the phrase “string” anywhere, the condition will return true. Other forms of shell globbing are allowed, too. If you’d like to match both “String” and “string”, you could use the following syntax:

if [[ "$stringvar" == *[sS]tring* ]]; then

Note that only general shell globbing is allowed. Bash-specific things like {1..4} or {foo,bar} will not work. Also note that the globbing will not work if you quote the right string. In this case you should leave it unquoted.
* The second difference is that word splitting is prevented. Therefore, you could omit placing quotes around string variables and use a condition like the following without problems:

if [[ $stringvarwithspaces != foo ]]; then

Nevertheless, the quoting string variables remains a good habit, so I recommend just to keep doing it.
* The third difference consists of not expanding filenames. I will illustrate this difference using two examples, starting with the old single-bracket situation:

if [ -a *.sh ]; then

The above condition will return true if there is one single file in the working directory that has a .sh extension. If there are none, it will return false. If there are several .sh files, bash will throw an error and stop executing the script. This is because *.sh is expanded to the files in the working directory. Using double brackets prevents this:

if [[ -a *.sh ]]; then

The above condition will return true only if there is a file in the working directory called “*.sh”, no matter what other .sh files exist. The asterisk is taken literally, because the double-bracket syntax does not expand filenames.
* The fourth difference is the addition of more generally known combining expressions, or, more specific, the operators “&&” and “||”. Example:

if [[ $num -eq 3 && "$stringvar" == foo ]]; then

The above condition returns true if $num is equal to 3 and $stringvar is equal to “foo”. The -a and -o known from the single-bracket syntax is supported, too.

Note that the and operator has precedence over the or operator, meaning that “&&” or “-a” will be evaluated before “||” or “-o”.
* The fifth difference is that the double-bracket syntax allows regex pattern matching using the “=~” operator. See the table for more information.

3. Double-parenthesis syntax

There also is another syntax for arithmetic (number-based) conditions, most likely adopted from the Korn shell:

if (( $num < = 5 )); then

The above condition is true if $num is less than or equal to 5. This syntax may seem more familiar to programmers. It features all the 'normal' operators, like "==", "<" and ">=”. It supports the “&&” and “||” combining expressions (but not the -a and -o ones!). It is equivalent to the built-in let command.
Table of conditions

The following table list the condition possibilities for both the single- and the double-bracket syntax. Save a single exception, the examples are given in single-bracket syntax, but are always compatible with double brackets.
1. File-based conditions:
Condition True if Example/explanation
[ -a existingfile ] file ‘existingfile’ exists. if [ -a tmp.tmp ]; then
rm -f tmp.tmp # Make sure we’re not bothered by an old temporary file
fi
[ -b blockspecialfile ] file ‘blockspecialfile’ exists and is block special. Block special files are special kernel files found in /dev, mainly used for ATA devices like hard disks, cd-roms and floppy disks.

if [ -b /dev/fd0 ]; then
dd if=floppy.img of=/dev/fd0 # Write an image to a floppy
fi
[ -c characterspecialfile ] file ‘characterspecialfile’ exists and is character special. Character special files are special kernel files found in /dev, used for all kinds of purposes (audio hardware, tty’s, but also /dev/null).

if [ -c /dev/dsp ]; then
cat raw.wav > /dev/dsp # This actually works for certain raw wav files
fi
[ -d directory ] file ‘directory’ exists and is a directory. In UNIX-style, directories are a special kind of file.

if [ -d ~/.kde ]; then
echo “You seem to be a kde user.”
fi
[ -e existingfile ] file ‘existingfile’ exists. (same as -a, see that entry for an example)
[ -f regularfile ] file ‘regularfile’ exists and is a regular file. A regular file is neither a block or character special file nor a directory.

if [ -f ~/.bashrc ]; then
source ~/.bashrc
fi
[ -g sgidfile ] file ‘sgidfile’ exists and is set-group-ID. When the SGID-bit is set on a directory, all files created in that directory will inherit the group of the directory.

if [ -g . ]; then
echo “Created files are inheriting the group ‘$(ls -ld . | awk ‘{ print $4 }’)’ from the working directory.”
fi
[ -G fileownedbyeffectivegroup ] file ‘fileownedbyeffectivegroup’ exists and is owned by the effective group ID. The effective group id is the primary group id of the executing user.

if [ ! -G file ]; then # An exclamation mark inverts the outcome of the condition following it
chgrp $(id -g) file # Change the group if it’s not the effective one
fi
[ -h symboliclink ] file ‘symboliclink’ exists and is a symbolic link. if [ -h $pathtofile ]; then
pathtofile=$(readlink -e $pathtofile) # Make sure $pathtofile contains the actual file and not a symlink to it
fi
[ -k stickyfile ] file ‘stickyfile’ exists and has its sticky bit set. The sticky bit has got quite a history, but is now used to prevent world-writable directories from having their contents deletable by anyone.

if [ ! -k /tmp ]; then # An exclamation mark inverts the outcome of the condition following it
echo “Warning! Anyone can delete and/or rename your files in /tmp!”
fi
[ -L symboliclink ] file ‘symboliclink’ exists and is a symbolic link. (same as -h, see that entry for an example)
[ -N modifiedsincelastread ] file ‘modifiedsincelastread’ exists and was modified after the last read. if [ -N /etc/crontab ]; then
killall -HUP crond # SIGHUP makes crond reread all crontabs
fi
[ -O fileownedbyeffectiveuser ] file ‘fileownedbyeffectiveuser’ exists and is owned by the user executing the script. if [ -O file ]; then
chmod 600 file # Makes the file private, which is a bad idea if you don’t own it
fi
[ -p namedpipe ] file ‘namedpipe’ exists and is a named pipe. A named pipe is a file in /dev/fd/ that can be read just once. See my bash tutorial for a case in which it’s used.

if [ -p $file ]; then
cp $file tmp.tmp # Make sure we’ll be able to read
file=”tmp.tmp” # the file as many times as we like
fi
[ -r readablefile ] file ‘readablefile’ exists and is readable to the script. if [-r file ]; then
content=$(cat file) # Set $content to the content of the file
fi
[ -s nonemptyfile ] file ‘nonemptyfile’ exists and has a size of more than 0 bytes. if [ -s logfile ]; then
gzip logfile # Backup the old logfile
touch logfile # before creating a fresh one.
fi
[ -S socket ] file ‘socket’ exists and is a socket. A socket file is used for inter-process communication, and features an interface similar to a network connection.

if [ -S /var/lib/mysql/mysql.sock ]; then
mysql –socket=/var/lib/mysql/mysql.sock # See this MySQL tip
fi
[ -t openterminal ] file descriptor ‘openterminal’ exists and refers to an open terminal. Virtually everything is done using files on Linux/UNIX, and the terminal is no exception.

if [ -t /dev/pts/3 ]; then
echo -e “\nHello there. Message from terminal $(tty) to you.” > /dev/pts/3 # Anyone using that terminal will actually see this message!
fi
[ -u suidfile ] file ‘suidfile’ exists and is set-user-ID. Setting the suid-bit on a file causes execution of that file to be done with the credentials of the owner of the file, not of the executing user.

if [ -u executable ]; then
echo “Running program executable as user $(ls -l executable | awk ‘{ print $3 }’).”
fi
[ -w writeablefile ] file ‘writeablefile’ exists and is writeable to the script. if [ -w /dev/hda ]; then
grub-install /dev/hda
fi
[ -x executablefile ] file ‘executablefile’ exists and is executable for the script. Note that the execute permission on a directory means that it’s searchable (you can see which files it contains).

if [ -x /root ]; then
echo “You can view the contents of the /root directory.”
fi
[ newerfile -nt olderfile ] file ‘newerfile’ was changed more recently than ‘olderfile’, or if ‘newerfile’ exists and ‘olderfile’ doesn’t. if [ story.txt1 -nt story.txt ]; then
echo “story.txt1 is newer than story.txt; I suggest continuing with the former.”
fi
[ olderfile -ot newerfile ] file ‘olderfile’ was changed longer ago than ‘newerfile’, or if ‘newerfile’ exists and ‘olderfile’ doesn’t. if [ /mnt/remote/remotefile -ot localfile ]; then
cp -f localfile /mnt/remote/remotefile # Make sure the remote location has the newest version of the file, too
fi
[ same -ef file ] file ‘same’ and file ‘file’ refer to the same device/inode number. if [ /dev/cdrom -ef /dev/dvd ]; then
echo “Your primary cd drive appears to read dvd’s, too.”
fi
2. String-based conditions:
Condition True if Example/explanation
[ STRING1 == STRING2 ] STRING1 is equal to STRING2. if [ "$1" == "moo" ]; then
echo $cow # Ever tried executing ‘apt-get moo’?
fi

Note: you can also use a single “=” instead of a double one.
[ STRING1 != STRING2 ] STRING1 is not equal to STRING2. if [ "$userinput" != "$password" ]; then
echo “Access denied! Wrong password!”
exit 1 # Stops script execution right here
fi
[ STRING1 \> STRING2 ] STRING1 sorts after STRING2 in the current locale (lexographically). The backslash before the angle bracket is there because the bracket needs to be escaped to be interpreted correctly. As an example we have a basic bubble sort:

(Don’t feel ashamed if you don’t understand this, it is a more complex example)

array=( linux tutorial blog )
swaps=1
while (( swaps > 0 )); do

swaps=0
for (( i=0; i < (( ${#array[@]} - 1 )) ; i++ )); do
if [ "${array[$i]}" \> “${array[$(( i + 1 ))]}” ]; then # Here is the sorting condition
tempstring=${array[$i]}
array[$i]=${array[$(( i + 1 ))]}
array[$(( i + 1 ))]=$tempstring
(( swaps=swaps + 1 ))
fi
done
done
echo ${array[@]} # Returns “blog linux tutorial”
[ STRING1 \< STRING2 ] STRING1 sorts before STRING2 in the current locale (lexographically).
[ -n NONEMPTYSTRING ] NONEMPTYSTRING has a length of more than zero. This condition only accepts valid strings, so be sure to quote anything you give to it.

if [ -n "$userinput" ]; then
userinput=parse($userinput) # Only parse if the user actually gave some input.
fi

Note that you can also omit the “-n”, as brackets with just a string in it behave the same.
[ -z EMPTYSTRING ] EMPTYSTRING is an empty string. This condition also accepts non-string input, like an uninitialized variable:

if [ -z $uninitializedvar ]; then
uninitializedvar=”initialized” # -z returns true on an uninitialized variable, so we initialize it here.
fi
Double-bracket syntax only:
[[ STRING1 =~ REGEXPATTERN ]] STRING1 matches REGEXPATTERN. If you are familiar with Regular Expressions, you can use this conditions to perform a regex match.

if [[ "$email" =~ "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b” ]]; then
echo “\$email contains a valid e-mail address.”
fi
3. Arithmetic (number-based) conditions:
Condition True if Example/explanation
[ NUM1 -eq NUM2 ] NUM1 is EQual to NUM2. These conditions only accept integer numbers. Strings will be converted to integer numbers, if possible. Some random examples:

if [ $? -eq 0 ]; then # $? returns the exit status of the previous command
echo “Previous command ran succesfully.”
fi

if [ $(ps -p $pid -o ni=) -ne $(nice) ]; then
echo “Process $pid is running with a non-default nice value”
fi

if [ $num -lt 0 ]; then
echo “Negative numbers not allowed; exiting…”
exit 1
fi
[ NUM1 -ne NUM2 ] NUM1 is Not Equal to NUM2.
[ NUM1 -gt NUM2 ] NUM1 is Greater Than NUM2.
[ NUM1 -ge NUM2 ] NUM1 is Greater than or Equal to NUM2.
[ NUM1 -lt NUM2 ] NUM1 is Less Than NUM2.
[ NUM1 -le NUM2 ] NUM1 is Less than or Equal to NUM2.
4. Miscellaneous conditions:
Condition True if Example/explanation
[ -o shelloption ] shell option ‘shelloption’ is enabled. Shell options modify the behaviour of bash, except a few unmodifiable ones that indicate the shell status.

if [ ! -o checkwinsize ] # An exclamation mark inverts the outcome of the condition following it
echo “Shell option checkwinsize is disabled; enabling it so you can resize you terminal window without problems.”
shopt -s checkwinsize # This shell option is modifiable
fi

if [ -o login_shell ]; then
echo “This a a login shell.” # This shell option is not modifiable

fi

With the double-parenthesis syntax, you can use the following conditions:
5. Double-parenthesis syntax conditions:
Condition True if Example/explanation
(( NUM1 == NUM2 )) NUM1 is equal to NUM2. These conditions only accept integer numbers. Strings will be converted to integer numbers, if possible. Some random examples:

if (( $? == 0 )); then # $? returns the exit status of the previous command
echo “Previous command ran succesfully.”
fi

if (( $(ps -p $pid -o ni=) != $(nice) )); then
echo “Process $pid is running with a non-default nice value”
fi

if (( $num < 0 )); then
echo "Negative numbers not allowed; exiting..."
exit 1
fi
(( NUM1 != NUM2 )) NUM1 is not equal to NUM2.
(( NUM1 > NUM2 )) NUM1 is greater than NUM2.
(( NUM1 >= NUM2 )) NUM1 is greater than or equal to NUM2.
(( NUM1 < NUM2 )) NUM1 is less than NUM2.
(( NUM1 <= NUM2 )) NUM1 is less than or equal to NUM2.

After this dry information load, here's a bit of explanation for those who want to know more...
Diving a little deeper

I said I'd tell more about the fact that if essentially checks the exit status of commands. And so I will. The basic rule of bash when it comes to conditions is 0 equals true, >0 equals false.
That’s pretty much the opposite of many programming languages where 0 equals false and 1 (or more) equals true. The reason behind this is that shells like bash deal with programs a lot. By UNIX convention, programs use an exit status for indicating whether execution went alright or an error occured. As a succesful execution doesn’t require any explanation, it needs only one exit status. If there was a problem, however, it is useful to know what went wrong. Therefore, 0 is used for a succesful execution, and 1-255 to indicate what kind of error occured. The meaning of the numbers 1-255 differs depending on the program returning them.

Anyway, if executes the block after then when the command returns 0. Yes, conditions are commands. The phrase [ $foo -ge 3 ] returns an exit status, and the other two syntaxes as well! Therefore, there’s a neat trick you can use to quickly test a condition:

[ $foo -ge 3 ] && echo true

In this example, “echo true” is only executed if “[ $foo -ge 3 ]” returns 0 (true). Why is that, you might ask. It’s because bash only evaluates a condition when needed. When using the and combining expression, both conditions need to be true to make the combining expression return true. If the first condition returns false, it doesn’t matter what the second one returns; the result will be false. Therefore, bash doesn’t evaluate the second condition, and that’s the reason why “echo true” is not executed in the example. This is the same for the or operator (“||”), where the second condition is not evaluated if the first one is true.

Well, so much for the diving. If you want to know even more, I’d like to point you to the Advanced Bash-Scripting Guide and maybe the Bash Reference Manual.’

Share