var=$test | bash |
set var = $test | tcsh |
The backslash before the dollar sign ($
) signals the shell to interpret the $
as any other ordinary character and not to associate any special meaning to it. You could also use single quotes ('
) around the $test variable to get the same result.
Using the Backtick to Replace a String with Output
You can use the backtick (`
) character to signal the shell to replace a string with its output when executed. This special character can be used in shell programs when you want the result of the execution of a command to be stored in a variable. For example, if you want to count the number of lines in a file called test.txt
in the current directory and store the result in a variable called var
, you can use the following command:
Command | Environment |
---|---|
var=`wc -l test.txt` | bash |
set var = `wc -l test.txt` | tcsh |
Comparison of Expressions in bash
Comparing values or evaluating the differences between similar bits of data — such as file information, character strings, or numbers — is a task known as bash
, a command called test
can be used to achieve comparisons of expressions. In tcsh
, you can write an expression to accomplish the same thing.
The bash
shell syntax provides a command named test to compare strings, numbers, and files. The syntax of the test
command is as follows:
test
or
[
Both forms of the test
commands are processed the same way by bash
. The test
commands support the following types of comparisons:
> String comparison
> Numeric comparison
> File operators
> Logical operators
String Comparison
The following operators can be used to compare two string expressions:
> =
— To compare whether two strings are equal
> !=
— To compare whether two strings are not equal
> -n
— To evaluate whether the string length is greater than zero
> -z
— To evaluate whether the string length is equal to zero
Next are some examples using these operators when comparing two strings, string1
and string2
, in a shell program called compare1
:
#!/bin/sh
string1='abc'
string2='abd'
if [ $string1 = $string2 ]; then
echo 'string1 equal to string2'
else
echo 'string1 not equal to string2'
fi
if [ $string2 != string1 ]; then
echo 'string2 not equal to string1'
else
echo 'string2 equal to string2'
fi
if [ $string1 ]; then
echo 'string1 is not empty'
else
echo 'string1 is empty'
fi
if [ -n $string2 ]; then
echo 'string2 has a length greater than zero'
else
echo 'string2 has length equal to zero'
fi
if [ -z $string1 ]; then