我做了一个带有if
的脚本需要几百行,因为它列出了所有可能性,我想知道是否可以将其大小减少到几行,因为我发现自己迷失了所有这些线条。以下是代码示例:
if [ "$player_position" = 1 ]; then
echo "Player is on the tile 1"
elif [ "$player_position" = 2 ]; then
echo "Player is on the tile 2"
elif [ "$player_position" = 3 ]; then
echo "Player is on the tile 3"
fi
等等。我想摆脱所有elif
,但保留所有可能性
PS:每个磁贴的名称都在一个变量中,如" tile_1_name"这个数字也必须改变
答案 0 :(得分:1)
如果您使用的是最新版本的bash(我相信4.4),您可以使用a "nameref"
# first check the bounds of the position
if (( 1 <= player_position && player_position <= max_upper_position )); then
declare -n tile="tile_${player_position}_name"
echo "Player is on the tile ${tile:-with no name}"
else
echo "Invalid player position: $player_position"
fi
但是,你应该停止使用&#34; dynamic&#34;变量名称如&#34; tile_1_name&#34;。而是使用数组:
tile_names[4]="Fourth tile"
...
echo "Player is on the tile ${tile_names[$player_position]:-with no name}"
答案 1 :(得分:0)
if [ "$player_position" -ge 1 -a "$player_position" -le 3 ]; then
echo "Player is on the tile $player_position"
fi
说明:
-ge
:大于或等于-le
:小于或等于-a
:逻辑AND 答案 2 :(得分:0)
您可以使用case
声明:
case "$player_position" in
[0-9])
echo "Player is on the tile $player_position"
;;
esac
答案 3 :(得分:-1)
你需要通过循环来完成。 例如:
Dataset<Row> valuesToUpdate = dataset.filter('conditionToFilterValues');
Dataset<Row> valuesNotToUpdate = dataset.except(valuesToUpdate);
valueToUpdate = valueToUpdate.withColumn('updatedColumn', lit('updateValue'));
Dataset<Row> updatedDataset = valuesNotToUpdate.union(valueToUpdate);