--Variationen, spezielle Variablen
read -p "Pick 3 colors: " c1 c2 c3
echo $c1
echo $c2
echo $c3
echo $0
echo $1
echo $2
echo $#
echo $@
./test a b c
./test
a
b
3
a b c
colors=(blue red green)
echo "${colors[@]}"
echo "${colors[0]}"
colors+=(pink white) #Hinzufügen eines Arrays
echo "${colors[@]}"
blue red green
blue
blue red green pink white
# + - * / % ** ++ --
n=1
((n++)) #n=2
((n=n+5)) #n=7
echo $n
((n=n/7)) #n=1
echo $n
if
read -p "name :" name
if [[ $name == "mhori" ]]; then
echo "welcome"
elif [[ $name =~ ^m ]]; then #Ab m
echo "Are you mhori?"
else
echo "you are not allowed"
fi
read -p "searching name:" name
if [[ -f $name ]]; then
echo "file $name exists"
elif [[ -d $name ]]; then
echo "directory $name exits"
fi
# = == != -z(Die Länge der Zeichenkette beträgt 0) =~(Reguläre Ausdrücke)
read -p "string: " str
if [[ -z $str ]]; then
echo "string is empty"
elif [[ $str =~ ^m ]]; then
echo "string starts with m"
else
echo $string
fi
for, while
for
colors=(blue red pink)
for color in ${colors[@]}; do
echo "I love $color"
done
I love blue
I love red
I love pink
while
i=0
while ((i < 10)); do
((i++))
if ((i == 3)); then
continue
elif ((i == 6)); then
break
fi
echo $i
done
1
2
4
5
while :
do
read -p "command : " cmd
if [[ $cmd == "quit" ]]; then
break
else
echo $cmd
fi
done
command : p
p
command : m
m
command : qiot
qiot
command : quit
## 1 ##
while read line; do
echo $line
done < colors.txt
## 2 ##
cat colors.txt | while read line
do
echo $line
done
case & select
case
read -p "Signal color : " color
case "$color" in
red)
echo "stop"
;;
blue|green)
echo "go"
;;
*)
echo "wrong signal"
esac
select
select color in red blue green yellow ; do
case "$color" in
red)
echo "stop"
;;
blue|green)
echo "go"
;;
yellow)
echo "caution"
;;
*)
echo "wrong signal"
break
esac
done
1) red
2) blue
3) green
4) yellow
#? 1
stop
#? 2
go
#? 3
go
#? 4
caution
#? 0
wrong signal
Unter Unix ist 0 eine normale Beendigung, 1 eine abnormale Beendigung und es ist nützlich zu wissen, dass Sie mit "$?" Überprüfen können.
hello() {
if [[ $1 == "mhori" ]]; then
echo "hello $1"
return 0
else
echo "goodbye $1"
return 1
fi
}
hello mhori; echo $? #hello mhori 0
hello mmm; echo $? #goodbye mmm 1
Recommended Posts