处理列表中的一个或多个对象

处理列表中的一个或多个对象

我编写了一个脚本,它将查找名称中包含空格的对象,并用下划线替换每个空格。对象类型基于单个对象选择。
作为替代选项,我如何处理所有对象类型?我在想也许是 if-then-else 以及内部 for 循环?

#!/bin/sh
printf "Choose object from the list below\n"
printf "**policy**\n**ipadd**r\n**subnet**\n**netmap**\n**netgroup**\n
**host**\n**iprange**\n**zonegroup**\n" | tee object.txt

read object
IFS="`printf '\n\t'`"
#   Find all selected object names that contain spaces
cf -TJK name "$object" q | tail -n +3 |sed 's/ *$//' |grep " " >temp
for x in `cat temp`
do
#   Assign the y variable to the new name
y=`printf "$x" | tr ' ' '_'`
#   Rename the object using underscores
cf "$object" modify name="$x" newname="$y"
done

答案1

当您想向用户呈现菜单时,请考虑以下select命令:

#  Ask the user which object type they would like to rename
objects=( policy netgroup zonegroup host iprange ipaddr subnet netmap )
PS3="Which network object type would you like to edit? "

select object in "${objects[@]}" all; do
    [[ -n "$object" ]] && break
done

if [[ "$object" == "all" ]]; then
    # comma separated list of all objects
    object=$( IFS=,; echo "${objects[*]}" )
fi

cf -TJK name "$object" q | etc etc etc
# ...........^ get into the habit of quoting your variables.

我假设这里。如果这不是您正在使用的 shell,请告诉我们。


如果你陷入没有数组的 shell 中,你可以这样做,因为对象是简单的单词:

objects="policy netgroup zonegroup host iprange ipaddr subnet netmap"
PS3="Which network object type would you like to edit? "

select object in $objects all; do     # $objects is specifically not quoted here ...
    [ -n "$object" ] && break
done

if [ "$object" = "all" ]; then
    object=$( set -- $objects; IFS=,; echo "$*" )        # ... or here
fi

cf -TJK name "$object" q | etc etc etc

相关内容