Upload
vy-nguyen
View
216
Download
0
Embed Size (px)
Citation preview
8/3/2019 C4 - Variables
1/17
Shell variables
Tutor: Lu Thanh Tr
Email: lttra hoasen.edu.vn
8/3/2019 C4 - Variables
2/17
Outline
Embedding documentation
urroun ng ex
Exporting variablesDefault values
8/3/2019 C4 - Variables
3/17
Shell variables
MYVAR=something
Variable name:
Do not use space ( )
8/3/2019 C4 - Variables
4/17
Embedding documentation in scripts #!/usr/bin/env bash
# cookbook filename: embedded_documentation
echo 'Shell script code goes here'
# Use a : NOOP and here document to embed documentation,
:
8/3/2019 C4 - Variables
5/17
=head1 LICENSE AND COPYRIGHT
=cut
END_OF_DOCS
8/3/2019 C4 - Variables
6/17
pod2html, pod2man
8/3/2019 C4 - Variables
7/17
Surrounding text
Example f o r F N i n 1 2 3 4 5
do
somescript /tmp/rep$FNport.txt done
=> somescript /tmp/rep${FN}bay.txt
8/3/2019 C4 - Variables
8/17
Export variables Make a variable is available in other shells
Example: export FNAME
ex ort SIZE
export MAX
...
MAX=2048 =
FNAME=/tmp/scratch
and at other times youll see:
export FNAME=/tmp/scratch
export MAX=2048
...
FNAME=/tmp/scratch2
8/3/2019 C4 - Variables
9/17
,
env: list only the exported variables
set | grep MYVAR
8/3/2019 C4 - Variables
10/17
Paramters in a shell
$ cat tricky.sh echo $1 $10 ${10}
./tricky.sh I II III IV V VI VII VIII IX X XI
I I0 X
$
8/3/2019 C4 - Variables
11/17
Parameters with blanks Unix acce ts the file name with blanks however we
have to use quote $ cat quoted.sh
ls -l "${1}"
$" ". .
-rw-r--r-- 1 smith users 28470 2007-01-11 19:22 Oh the Waste
8/3/2019 C4 - Variables
12/17
$* and $@
ls vocals.mp3
cool music.mp3
tophit.mp3 or n
for FN in $*
for FN in $@
8/3/2019 C4 - Variables
13/17
Counting arguments with $# #!/usr/bin/env bash
# cookbook filename: check_arg_count
# Check for the correct # of ar uments:
# Use this syntax or use: if [ $# -lt 3 ]
if (( $# < 3 ))
then
printf "%b" "Error. Not enough arguments.\n" >&2
printf "%b" "usage: myscript file1 op file2\n" >&2
exit 1
then
printf "%b" "Error. Too many arguments.\n" >&2
rintf "%b" "usa e: m scri t file1 o file2\n" >&2
exit 2
else
printf "%b" "Argument count correct. Proceeding...\n"
fi
8/3/2019 C4 - Variables
14/17
Arguments #!/usr/bin/env bash
# parse the optional argument
=
if [[ $1 = -v ]] then
= ;
shift;
fi e rea wor s ere
for FN in "$@"
do
== then
echo changing $FN
chmod 0750 "$FN"
done
8/3/2019 C4 - Variables
15/17
Default value with ${:-}
= -" "
Set and Unset $ echo ${HOME:=/tmp}
/home/uid002
$ unset HOME # generally not wise to do
/tmp
$ echo $HOME
8/3/2019 C4 - Variables
16/17
Null default value with ${=}
$ echo ${HOME=/tmp} # no substitution needed
/home/uid002
$ HOME=""
=
$ unset HOME
$ HOME=${HOME:?Error} ec o = tmp w su st tute
/tmp
$ echo $HOME
/tmp
8/3/2019 C4 - Variables
17/17
Array
=
=> array with 4 elements= " " " "
=> array with 2 elements
=colors[3] = greencolors[4] = blue
=> echo ${colors[0]}
filearray=( `cat filename | tr '\n' ' '`)
=>echo ${filearray[0]}