Shell-Script

處理列表中的一個或多個對象

  • March 26, 2018

我編寫了一個腳本,它將查找名稱中包含空格的對象,並將每個空格替換為下劃線。對像類型基於單個對象選擇。

如何處理所有對像類型作為替代選項?我在想可能是 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

當您想向使用者顯示菜單時,請考慮以下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.

我在這裡假設bash。如果這不是您使用的外殼,請告訴我們。


如果你被困在一個沒有數組的 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

引用自:https://unix.stackexchange.com/questions/432799