CS246-F20-1.14-Bash-test
Lecture 1.14
• Writing bash scripts:
– Command substitution $()
– test
CS246
Command substitution:
$() (and the older backtick)
• Sometimes you want to run a bash command
and use the output immediately
$ which ls # which file runs when I type “ls”?
/usr/local/opt/coreutils/libexec/gnubin/ls
$ file /bin/ls # what kind of file is this?
/usr/local/opt/coreutils/libexec/gnubin/ls: Mach-O 64-bit
executable x86_64
$ file $(which ls) # Combine ’em: preferred bash syntax
/usr/local/opt/coreutils/libexec/gnubin/ls: Mach-O 64-bit
executable x86_64
$ file `which ls` # backtick is older syntax, don’t use
/usr/local/opt/coreutils/libexec/gnubin/ls: Mach-O 64-bit
executable x86_64
test
• test command compares strings, integers and queries files
• The test expression is constructed using the following:
test operation priority
!expr not highest
\( expr \) ordering
expr1 -a expr2 AND
expr1 -o expr2 OR lowest
test
Test Meaning Test Meaning
str1 = str2 equal** -e file File exists
str1 != str2 not equal -d file File exists and
is a directory
int1 –eq int2 equal -f file File exists and
is a plain file
int1 –ne int2 not equal -r file File exists and I have
read permission
int1 –ge int2 >= -w file File exists and I have
write permission
int1 –gt int2 > -x file File exists and I have
execute permission
int1 –le int2 <=
int1 –lt int2 <
**Note single equals sign "=" for testing equivalence, not "=="
test
• Can say test or use square brackets
– Square brackets must have a space after "[" and before "]"
• Logical operators -a (and) and -o (or) evaluate both
operands
i.e., not short circuit evaluation
• test returns 0 if expression is true and 1 otherwise
– This is very counter intuitive!
$ i=3
$ whoami
migod
$ test $i -lt 4
$ echo ${?}
0
$ test $(whoami) = jfdoe
$ echo ${?}
1
$ [ $(whoami) = migod ]
$ echo ${?}
0
$ test 2 -lt ${i} –o $(whoami) = jfdoe
$ echo ${?}
0
# integer test
# true
# string test
# false
# similar but with []
# Yes officer, it's
me
# compound test
# true
$ [ -e q1.cc ]
$ echo ${?}
0
$ [ -d /tmp -a -x /tmp -a -w /tmp ]
$ echo $?
0
$ [ -d /usr/bin ]
$ echo $?
0
$ [ -w /usr/bin ]
$ echo $?
1
$ [ -e ${HOME}/fnord ]
$ echo $?
1
There is a file or dir
named q1.cc in this dir
/tmp is a dir + I have
wx permissions there
/usr/bin is a dir, but I
don't have w permission
There is no file named
fnord in my home dir.
See, I told you.
End
CS246