Bash Script Flashcards
What is set command?
set returns all environment variables + extras like functions etc which env would not return
What is $#?
Number of all parameters
What is $0, $1
Program name, first argument
What is $*
All arguments
How to print parameter 12?
${12}
What does this do?
var=”one two three four five”
set – $var
sets the input parameters as one two three four five
for i do echo $i done
when range is neglected the for loop loops through the input parameters so $i is $1, $2 etc
Difference between echo $varname and echo “$varname”?
Same if there are no multiple white spaces. In case there are, $varname will print only 1 space while “$varname” will print all the spaces.
hello=”K L M”
1. Output: echo “$hello”
2. Output: echo $hello
3. Output: echo ‘$hello’
- K L M
- K L M
- $hello
IFS=’!’ read a b
echo a is $a
echo b is $b
- input = kostas mylonas
- input = kostas!mylonas
- a is kostas mylonas
b is
2.
a is kostas
b is mylonas
Default IFS is whitespace
str=”kostas”
echo ${str^^}
KOSTAS
str=”KOSTAS”
echo ${str,,}
kostas
str=”KOStas”
echo ${str,}
kOStas
str=”kOstAs”
echo ${str^}
KOstAs
anArray=(‘el1’ ‘el2’ ‘el3’)
1. echo ${anArray[@]}
2. echo ${!anArray[@]}
3. echo ${#anArray[@]}
- whole array: el1 el2 el3
- array indices: 0 1 2
- size of array: 3
a=2
let b = a+2
Will it work? If not what should be changed to make it work
No, space is not allowed. If you want to use space then include evreything in “” like
let “b = a+2”
How to properly use expr command?
Always put it inside ` ` and spaces are mandatory!
e.g.
a =expr 3 + 5
a =expr $k + 3
string=ABigString
pos=4
length=6
z=expr substr $string $pos $length
echo $z
Output?
gStrin
What is
“echo $?”
Prints the exit status of the last executed command
set – echo "p1 p2 p3 p4 p5 p6"
for j in ${*:2:3}
do
echo -n $j
done
echo
p2p3p4
“Start from 2nd param and use up untill 3 params”
set – echo "p1 p2 p3 p4 p5 p6"
for j in ${*:2}
do
echo -n $j
done
echo
p2p3p4p5p6
“Start from 2nd param and go till the end”
!export my_new_env_var=”Harry”
create env var only for current session. If you want it globally then you have to go through bashrc
How to multiply using expr?
a=expr 5 \* 3
# 15 – with expr in multiplication use *
z=expr substr $string $pos $length
from string start from pos and take up to length chars
ABigString pos = 4 len = 6 will give
gStrin