我将创建一个脚本,当用户输入为“foo”时,该脚本应打印“foo”或“bar”,然后打印“bar”,或者当用户输入为“bar”时,打印“foo”,否则显示“invalid”细绳”。这是我正在编写的脚本:
foo=$x
bar=$y
val=$val
echo "enter the val = $val "
read $val
if [ "$val" = "$x" ]
then echo "bar"
elif [ "$val" = "$y" ]
then echo "foo"
else echo "invalid string"
fi
我是脚本新手,所以我不太了解。
答案1
我认为这就是你所需要的:
#!/bin/bash
foo="foo"
bar="bar"
val=""
read -p "Enter the var: " val
if [ "$val" == "$foo" ]; then
echo "$bar"
else
if [ "$val" == "$bar" ]; then
echo "$foo"
else
echo "Invalid string"
fi
fi
您可以将if...else
块替换为 a case
(当可能的选项太多时,这会派上用场):
case "$val" in
"$foo")
echo "$bar"
;;
"$bar")
echo "$foo"
;;
*)
echo "Invalid string"
;;
esac