Bash notes
From OriWiki
Contents |
currently executed script path
I wonder if there's a simpler way:
this_script_path=$(cd -P -- "$(dirname -- "$0")" && pwd -P) echo $this_script_path
debugging bash
The following will cause a verbose execution of a script
bash -x check.sh
redirection
redirection of the error stream
$app 2> error.out
redirection of both stdout and stderr to a file
$app &> all.out
see [1]
set environment variable
MYVAR=MY_VAR_VALUE export MYVAR
export
export MYVAR='set and export in one command'
exporting an environment variable make it accessible for applications that are invoked from the shell. For example, the following bash script:
#!/bin/bash echo $MYVAR
Will print nothing if MYVAR was set but not exported
The same will happen with the following C++ application:
#include <iostream>
#include <cstdlib>
int main() {
char *myvar = std::getenv("MYVAR");
std::cout << "MYVAR= " << myvar << '\n';
}
Sample script
#!/bin/sh
#this is a comment
#invoke a program
#../../exercises/ex2/q3 &
# usage of `expression`
grep `whoami` /etc/passwd
# arguments given to the script
echo the number of arguments given to this script: $#
echo the name of this script: $0
echo the first four arguments are: $1 $2 $3 $4
echo
# arithmetic expressions
echo the expression 2 + 3 equals: `expr 2 + 3`
echo the expression 2 \* 3 equals: `expr 2 \* 3`
#variables
a=17 #note that a = 17 (with spaces) will not set a value to a
b=`expr $a + 7`
echo -e a=$a "\n"b=$a+7 "\n"b=$b
#if statement
if [ $# -ne 0 ]
then
if [ $1 = hey ]
then
echo the first argument is hey
else
echo the first argument is not hey
fi
fi
# while loop
a1=1
a2=1
while [ $a2 -lt 50 ] #the spaces are important
do
echo -n $a1 " "
a3=`expr $a1 + $a2`
a1=$a2
a2=$a3
done
echo
#until loop
until [ 10 -gt $a1 ]
do
echo -n $a1 ""
a1=`expr $a1 - 1`
done
echo
#for loop
names="yosi pesi moshe tzili gile"
c=1
for n in $names
do
echo name $c: $n
c=`expr $c + 1`
done
Submit script
#! /bin/sh
if [ $# -ne 1 ]
then
echo -e "usage:\n" $0 "<ex num>"
exit 1
fi
if !(test -r readme) # FILE exists and is readable
then
echo "no readme file !"
exit 1
fi
if !(test -r makefile)
then
echo "no makefile file !"
exit 1
fi
tmpName=tmp
count=1
while true
do
tmpDir=$tmpName$count
if !(test -r $tmpDir)
then
break
fi
count=`expr $count + 1`
done
tarName=ex$1.tgz
echo "----------making tar.."
tar czvf $tarName *.cpp *.h makefile readme
echo "----------creating directory" $tmpDir ".."
mkdir $tmpDir
echo "----------copying tgz to" $tmpDir ".."
cp $tarName $tmpDir
cd $tmpDir
echo "----------extracting tgz.."
tar xzvf $tarName
echo "----------make.."
make
echo "----------run.."
make run
cd ..
rm -fr $tmpDir
echo -e "\n\n ------All seems to be ok."
exit 0

