else
echo 'dir1 is not a directory'
fi
if [ -f $dir1 ]; then
echo 'dir1 is a regular file'
else
echo 'dir1 is not a regular file'
fi
if [ -r $file1 ]; then
echo 'file1 has read permission'
else
echo 'file1 does not have read permission'
fi
if [ -w $file1 ]; then
echo 'file1 has write permission'
else
echo 'file1 does not have write permission'
fi
if [ -x $dir1 ]; then
echo 'dir1 has execute permission'
else
echo 'dir1 does not have execute permission'
fi
If you execute the shell program, you get the following results:
dir1 is a directory
file1 is a regular file
file1 has read permission
file1 does not have write permission
dir1 has execute permission
Logical Operators
Logical operators are used to compare expressions using Boolean logic, which compares values by using characters representing NOT, AND, and OR.
> !
—To negate a logical expression
> -a
— To logically AND two logical expressions
> -o
— To logically OR two logical expressions
This example named logic
uses the file and directory mentioned in the previous compare3
example:
#!/bin/sh
if [ -x file1 -a -x dir1 ]; then
echo file1 and dir1 are executable
else
echo at least one of file1 or dir1 are not executable
fi
if [ -w file1 -o -w dir1 ]; then
echo file1 or dir1 are writable
else
echo neither file1 or dir1 are executable
fi
if [ ! -w file1 ]; then
echo file1 is not writable
else
echo file1 is writable
fi
If you execute logic
, it yields the following result:
file1 and dir1 are executable
file1 or dir1 are writable
file1 is not writable
Special Statements: for
, while
, and Others
Bash comes with a variety of built-in statements to handle more complex condition checks such as loops and switch blocks. As with many things, bash
shares the same syntax, so these next sections are applicable to both shells.
The for
Statement
The for
statement is used to execute a set of commands once each time a specified condition is true. The for
statement has a number of formats. The first format used by bash
is as follows:
for curvar in list
do
done
This form should be used if you want to execute
once for each value in list
. For each iteration, the current value of the list is assigned to vcurvar
. list
can be a variable containing a number of items or a list of values separated by spaces. The second format is as follows:
for curvar
do
done
In this form, the
are executed once for each of the positional parameters passed to the shell program. For each iteration, the current value of the positional para meter